text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Find broken symlinks with Python If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux?
A: Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files share an inode.
Therefore, something like find . -type f -exec test \{} -ef /path/to/file \; -print works for hard link testing to a specific file.
Which brings me to reading man test and the mentions of -L and -h which both work on one file and return true if that file is a symbolic link, however that doesn't tell you if the target is missing.
I did find that head -0 FILE1 would return an exit code of 0 if the file can be opened and a 1 if it cannot, which in the case of a symbolic link to a regular file works as a test for whether it's target can be read.
A: A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.
A typical mistake is to write something like:
if os.path.exists(path):
os.unlink(path)
The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)
So, in your particular case, I would probably do:
try:
os.stat(path)
except OSError, e:
if e.errno == errno.ENOENT:
print 'path %s does not exist or is a broken symlink' % path
else:
raise e
The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.
So, I guess you have no choice than to break the atomicity, and do something like
if not os.path.exists(os.readlink(path)):
print 'path %s is a broken symlink' % path
A: os.path
You may try using realpath() to get what the symlink points to, then trying to determine if it's a valid file using is file.
(I'm not able to try that out at the moment, so you'll have to play around with it and see what you get)
A: I used this variant, When symlink is broken it will return false for the path.exists and true for path.islink, so combining this two facts we may use the following:
def kek(argum):
if path.exists("/root/" + argum) == False and path.islink("/root/" + argum) == True:
print("The path is a broken link, location: " + os.readlink("/root/" + argum))
else:
return "No broken links fond"
A: This is not atomic but it works.
os.path.islink(filename) and not os.path.exists(filename)
Indeed by RTFM
(reading the fantastic manual) we see
os.path.exists(path)
Return True if path refers to an existing path. Returns False for broken symbolic links.
It also says:
On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
So if you are worried about permissions, you should add other clauses.
A: os.lstat() may be helpful. If lstat() succeeds and stat() fails, then it's probably a broken link.
A: I'm not a python guy but it looks like os.readlink()? The logic I would use in perl is to use readlink() to find the target and the use stat() to test to see if the target exists.
Edit: I banged out some perl that demos readlink. I believe perl's stat and readlink and python's os.stat() and os.readlink()are both wrappers for the system calls, so this should translate reasonable well as proof of concept code:
wembley 0 /home/jj33/swap > cat p
my $f = shift;
while (my $l = readlink($f)) {
print "$f -> $l\n";
$f = $l;
}
if (!-e $f) {
print "$f doesn't exist\n";
}
wembley 0 /home/jj33/swap > ls -l | grep ^l
lrwxrwxrwx 1 jj33 users 17 Aug 21 14:30 link -> non-existant-file
lrwxrwxrwx 1 root users 31 Oct 10 2007 mm -> ../systems/mm/20071009-rewrite//
lrwxrwxrwx 1 jj33 users 2 Aug 21 14:34 mmm -> mm/
wembley 0 /home/jj33/swap > perl p mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p mmm
mmm -> mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p link
link -> non-existant-file
non-existant-file doesn't exist
wembley 0 /home/jj33/swap >
A: I had a similar problem: how to catch broken symlinks, even when they occur in some parent dir? I also wanted to log all of them (in an application dealing with a fairly large number of files), but without too many repeats.
Here is what I came up with, including unit tests.
fileutil.py:
import os
from functools import lru_cache
import logging
logger = logging.getLogger(__name__)
@lru_cache(maxsize=2000)
def check_broken_link(filename):
"""
Check for broken symlinks, either at the file level, or in the
hierarchy of parent dirs.
If it finds a broken link, an ERROR message is logged.
The function is cached, so that the same error messages are not repeated.
Args:
filename: file to check
Returns:
True if the file (or one of its parents) is a broken symlink.
False otherwise (i.e. either it exists or not, but no element
on its path is a broken link).
"""
if os.path.isfile(filename) or os.path.isdir(filename):
return False
if os.path.islink(filename):
# there is a symlink, but it is dead (pointing nowhere)
link = os.readlink(filename)
logger.error('broken symlink: {} -> {}'.format(filename, link))
return True
# ok, we have either:
# 1. a filename that simply doesn't exist (but the containing dir
does exist), or
# 2. a broken link in some parent dir
parent = os.path.dirname(filename)
if parent == filename:
# reached root
return False
return check_broken_link(parent)
Unit tests:
import logging
import shutil
import tempfile
import os
import unittest
from ..util import fileutil
class TestFile(unittest.TestCase):
def _mkdir(self, path, create=True):
d = os.path.join(self.test_dir, path)
if create:
os.makedirs(d, exist_ok=True)
return d
def _mkfile(self, path, create=True):
f = os.path.join(self.test_dir, path)
if create:
d = os.path.dirname(f)
os.makedirs(d, exist_ok=True)
with open(f, mode='w') as fp:
fp.write('hello')
return f
def _mklink(self, target, path):
f = os.path.join(self.test_dir, path)
d = os.path.dirname(f)
os.makedirs(d, exist_ok=True)
os.symlink(target, f)
return f
def setUp(self):
# reset the lru_cache of check_broken_link
fileutil.check_broken_link.cache_clear()
# create a temporary directory for our tests
self.test_dir = tempfile.mkdtemp()
# create a small tree of dirs, files, and symlinks
self._mkfile('a/b/c/foo.txt')
self._mklink('b', 'a/x')
self._mklink('b/c/foo.txt', 'a/f')
self._mklink('../..', 'a/b/c/y')
self._mklink('not_exist.txt', 'a/b/c/bad_link.txt')
bad_path = self._mkfile('a/XXX/c/foo.txt', create=False)
self._mklink(bad_path, 'a/b/c/bad_path.txt')
self._mklink('not_a_dir', 'a/bad_dir')
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def catch_check_broken_link(self, expected_errors, expected_result, path):
filename = self._mkfile(path, create=False)
with self.assertLogs(level='ERROR') as cm:
result = fileutil.check_broken_link(filename)
logging.critical('nothing') # trick: emit one extra message, so the with assertLogs block doesn't fail
error_logs = [r for r in cm.records if r.levelname is 'ERROR']
actual_errors = len(error_logs)
self.assertEqual(expected_result, result, msg=path)
self.assertEqual(expected_errors, actual_errors, msg=path)
def test_check_broken_link_exists(self):
self.catch_check_broken_link(0, False, 'a/b/c/foo.txt')
self.catch_check_broken_link(0, False, 'a/x/c/foo.txt')
self.catch_check_broken_link(0, False, 'a/f')
self.catch_check_broken_link(0, False, 'a/b/c/y/b/c/y/b/c/foo.txt')
def test_check_broken_link_notfound(self):
self.catch_check_broken_link(0, False, 'a/b/c/not_found.txt')
def test_check_broken_link_badlink(self):
self.catch_check_broken_link(1, True, 'a/b/c/bad_link.txt')
self.catch_check_broken_link(0, True, 'a/b/c/bad_link.txt')
def test_check_broken_link_badpath(self):
self.catch_check_broken_link(1, True, 'a/b/c/bad_path.txt')
self.catch_check_broken_link(0, True, 'a/b/c/bad_path.txt')
def test_check_broken_link_badparent(self):
self.catch_check_broken_link(1, True, 'a/bad_dir/c/foo.txt')
self.catch_check_broken_link(0, True, 'a/bad_dir/c/foo.txt')
# bad link, but shouldn't log a new error:
self.catch_check_broken_link(0, True, 'a/bad_dir/c')
# bad link, but shouldn't log a new error:
self.catch_check_broken_link(0, True, 'a/bad_dir')
if __name__ == '__main__':
unittest.main()
A: For Python 3, you can use the pathlib module. From its docs,
If the path points to a symlink, exists() returns whether the symlink points to an existing file or directory.
So this works too.
import pathlib
path = pathlib.Path("/path/to/somewhere")
if path.is_symlink() and not path.exists():
print(f"found dangling symlink at {path}")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: How to split a byte array I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:
byte[] largeBytes = [1,2,3,4,5,6,7,8,9];
byte[] smallPortion;
smallPortion = split(largeBytes, 3);
smallPortion would equal 1,2,3,4
largeBytes would equal 5,6,7,8,9
A: Try this one:
private IEnumerable<byte[]> ArraySplit(byte[] bArray, int intBufforLengt)
{
int bArrayLenght = bArray.Length;
byte[] bReturn = null;
int i = 0;
for (; bArrayLenght > (i + 1) * intBufforLengt; i++)
{
bReturn = new byte[intBufforLengt];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);
yield return bReturn;
}
int intBufforLeft = bArrayLenght - i * intBufforLengt;
if (intBufforLeft > 0)
{
bReturn = new byte[intBufforLeft];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);
yield return bReturn;
}
}
A: In C# with Linq you can do this:
smallPortion = largeBytes.Take(4).ToArray();
largeBytes = largeBytes.Skip(4).Take(5).ToArray();
;)
A: FYI. System.ArraySegment<T> structure basically is the same thing as ArrayView<T> in the code above. You can use this out-of-the-box structure in the same way, if you'd like.
A: As Eren said, you can use ArraySegment<T>. Here's an extension method and usage example:
public static class ArrayExtensionMethods
{
public static ArraySegment<T> GetSegment<T>(this T[] arr, int offset, int? count = null)
{
if (count == null) { count = arr.Length - offset; }
return new ArraySegment<T>(arr, offset, count.Value);
}
}
void Main()
{
byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var p1 = arr.GetSegment(0, 5);
var p2 = arr.GetSegment(5);
Console.WriteLine("First array:");
foreach (byte b in p1)
{
Console.Write(b);
}
Console.Write("\n");
Console.WriteLine("Second array:");
foreach (byte b in p2)
{
Console.Write(b);
}
}
A: This is how I would do that:
using System;
using System.Collections;
using System.Collections.Generic;
class ArrayView<T> : IEnumerable<T>
{
private readonly T[] array;
private readonly int offset, count;
public ArrayView(T[] array, int offset, int count)
{
this.array = array;
this.offset = offset;
this.count = count;
}
public int Length
{
get { return count; }
}
public T this[int index]
{
get
{
if (index < 0 || index >= this.count)
throw new IndexOutOfRangeException();
else
return this.array[offset + index];
}
set
{
if (index < 0 || index >= this.count)
throw new IndexOutOfRangeException();
else
this.array[offset + index] = value;
}
}
public IEnumerator<T> GetEnumerator()
{
for (int i = offset; i < offset + count; i++)
yield return array[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
IEnumerator<T> enumerator = this.GetEnumerator();
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
class Program
{
static void Main(string[] args)
{
byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5);
ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5);
Console.WriteLine("First array:");
foreach (byte b in p1)
{
Console.Write(b);
}
Console.Write("\n");
Console.WriteLine("Second array:");
foreach (byte b in p2)
{
Console.Write(b);
}
Console.ReadKey();
}
}
A: I'm not sure what you mean by:
I would like to split the byte array at a certain point(index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation.
In most languages, certainly C#, once an array has been allocated, there is no way to change the size of it. It sounds like you're looking for a way to change the length of an array, which you can't. You also want to somehow recycle the memory for the second part of the array, to create a second array, which you also can't do.
In summary: just create a new array.
A: You can't. What you might want is keep a starting point and number of items; in essence, build iterators. If this is C++, you can just use std::vector<int> and use the built-in ones.
In C#, I'd build a small iterator class that holds start index, count and implements IEnumerable<>.
A: I tried different algorithms :
*
*Skip().Take() => the worst, by far
*Array.Copy
*ArraySegment
*new Guid(int, int16, int16 ...)
The latest being the fastest I'm now using this extension method:
public static Guid ToGuid(this byte[] byteArray, int offset)
{
return new Guid(BitConverter.ToInt32(byteArray, offset), BitConverter.ToInt16(byteArray, offset + 4), BitConverter.ToInt16(byteArray, offset + 6), byteArray[offset + 8], byteArray[offset + 9], byteArray[offset + 10], byteArray[offset + 11], byteArray[offset + 12], byteArray[offset + 13], byteArray[offset + 14], byteArray[offset + 15]);
}
With a byte array with 10000000 guids:
Done (Skip().Take()) in 1,156ms (for only 100000 guids :))
Done (Array.Copy) in 1,219ms
Done (ToGuid extension) in 994ms
Done (ArraySegment) in 2,411ms
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: Automate Syncing Oracle Tables With MySQL Tables The university I work at uses Oracle for the database system. We currently have programs we run at night to download what we need into some local Access tables for our testing needs. Access is getting to small for this now and we need something bigger. Also, the nightly jobs require constant maintance to keep working (because of network issues, table changes, bad code :) ) and I would like to eliminate them to free us up for more important things.
I am most familiar with MySQL so I setup a test MySQL server. What is the best way to automate copying the needed tables from Oracle to MySQL?
Edit: I accepted the answer. I don't like the answer but it seems to be correct based on further research and the lack of other answers provided. Thanks to all for pondering my question and answering it.
A: I don't think there is really anything that is going to do this. If you could setup a local Oracle database, then most likely you could as oracle has various means of keeping two databases "in sync", provided they are both Oracle.
If you must use mysql, then likely you are going to just have to write something to sync the data, this is of course always going to run in the same problems you currently have with the access "database".
You could setup something with HSODBC and triggers, but
*
*I've found HSODBC to be very memory hungry
*This is only going to add more load to your DB, which you say is already heavily loaded during the day.
If the main thing you are doing is wanting a local Test copy of your oracle database, you would be best to setup syncing with a local version of oracle, as far as I can tell from the licenses, oracle is free for development copies ( I have seen some posts to the contrary, but if you find that is the case, you could always use something like Oracle XE)
A: Could you just copy the Oracle tables and then set them up as linked tables in MS Access? This way the front-end stays the same plus you keep everything in Oracle (less moving parts than exporting and importing).
A: As Kellyn said, there are lots of free tools. One of them is SQLWorkbench http://www.sql-workbench.net/, which works with any JDBC database, so MySQL and Oracle should work.
It can create tables in Oracle if needed, or just only copy over the (updated) data.
A: There are many tool available to migrate data from oracle to mysql if your database is not very complicated.
You can use open source tools like Kettle pentaho ETL tool or paid enterprise tools like DB convert: https://dbconvert.com/oracle/mysql/
Lastly you can write a script or program that migrates the data.
Please find links related to your question:
https://dba.stackexchange.com/questions/150343/how-to-sync-a-mysql-db-with-a-oracle-db
Migrate from Oracle to MySQL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I move an item from one menu to another? In the Visual Studio designer, how do you move a menu item from one menu to another?
I would assume drag and drop would work, but it seems to only work within a menu for me.
I usually resort to editing the .Designer.cs files by hand.
A: Right-click, cut, and paste works just fine for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SQL 2005 Reporting Services custom report item (CRI) - what are the limits? Reading MSDN (and other sources) about custom report items (CRI) for reporting services 2005. It looks like I'm limited to generating a bitmap. Not even with some mapping overlay for detecting mouse clicks on it. Is there away to go around this? There are two things I would like to do:
*
*Embed HTML directly into the report, to format dynamic text.
*Embed flash (swf) control in the report. This could be done with HTML if the previous point is possible. But maybe there is another way
Any suggestions? What am I missing?
A: You didn't missing anything.
For me, like you mentioned, the main disadvantage is, that with a CRI you can only render images. You don't get any scalable text or something similar.
If you want include swf, you need to render it as static image.
A: You can render the report as HTML and include the report using a floating frame in a page with the swf file. You can use functions to format dynamic text. SSRS 2008 solves some of these problems with the "richly" formated textbox (not RTF). it may worth a look, if it's an option.
A: You might want to take a look at Data Dynamics Reports which has all of the RS features and has better support for custom report items with a complete API not just bitmaps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL Server - Dirty Reads Pros & Cons Why should I or shouldn't I use dirty reads:
set transaction isolation level read uncommitted
in SQL Server?
A: Generally when you need to do a sizeable (or frequent) queries to busy tables, where read committed would possibly be blocked by locks from uncommited transactions, but ONLY when you can live with inaccurate data.
As an example, on a gaming web site I worked on recently there was a summary display of some stats about recent games, this was all based on dirty reads, it was more important for us to include then exclude the transactional data not yet committed (we knew anyway that few, if any, transactions would be backed out), we felt that on average the data would be more accurate that way.
A: From MSDN:
When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction.
Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity.
A: use it if you want the data back right away and it is not that important if it is right
do not use if if the data is important to be correct or if you are doing updates with it
Also take a look at snapshot isolation which has been introduced in sql server 2005
A: The Thing is when you want to read the data before committing, we can do with the help of set transaction isolation level read uncommitted, the data may, or may not change.
We can read the data by using the query:
Select * from table_name with(nolock)
This is applicable to only read uncommitted isolation level.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: DCOM: CoCreateInstanceEx returns E_ACCESSDENIED I'm working on a DCOM application with the server and client on two machines, both of which are running WinXP with Service Pack 2. On both machines, I'm logged in with the same username and password.
When the client on one machine calls CoCreateInstanceEx, asking the other machine to start up the server application, it returns E_ACCESSDENIED.
I tried going into the server app's component properties in dcomcnfg and giving full permisions to everyone for everything, but that didn't help.
What do I need to do to allow this call to succeed?
Update: When the server app is running on a Windows 2000 box, I do not get this error; CoCreateInstanceEx returns S_OK.
A: Right, so if your Authentication level is set to Default. What is the authentication level set to in the Default Settings? Just out of interest. (although the fact that it works to a 2000 box probably makes that redundant)
EDIT:
Also: I seem to remember doing a lot of rebooting when I used to play/work with DCOM so maybe a quick reboot of both machines when you're happy with the dcomcnfg settings wouldn't go amis either.
A: If the PCs aren't both members of the same domain, you need to also given launch & access permissions to "ANONYMOUS LOGON". "Everyone" does not include this.
A: Three things to check:
1) Go back to dcomcnfg and make try making sure that not just the access security but also the "launch permissions" section contains the appropriate security users or groups.
2) Ensure that the Authentication Level is set to something else other than "None"
3) Also check that the location on disk that the component is located is actually accessible to the account configured in the security permissions you set.
EDIT:
One more: Are you calling CoInitialiseSecurity() first too? That rings a bell!
EDIT2:
Based on your update: Try dropping the firewalls completely on both XP machines and see if that makes a difference. You may need to let DCOM through explicitly.
A: What is the flavor of your Windows 2000 box, btw? Professional, Server, Adv Server...
Also, is there a difference between domain membership between the two (one on a domain, the other not, different domains, etc...?)
One more thing - DCOM errors will appear in the System event log at times - especially for object creation - did you check there for clues?
A: I had the exact same problem.
The problem happens in machines that have XP SP2+ OS or newer.
I solved it using the following steps:
*
*Verify that both client and server computers are on the same domain.
*You need to use the same user in both computers, or, if you want to use different users in client and server you need to make sure that both client and server users have privliges on both computers (in particular - make sure that they are members of Distributed COM users group.
*open Componenet services MMC (run dcomcnfg).
*Go to My Computer->Properties->Default Properties and make sure that Default Impersenation Level is "Identify"
*Go to COM Security tab, in both in Access permissions and Launch and activation permissions go to Edit Limits, and add Local and Remote access permissions to the client and server users of your COM application
*Make sure that you have a firewall exception in port 135 for your application...
I hope this helps you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to stop NTFS volume auto-mounting on OS X? I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.
Basically, I have an external disk with two volumes:
One is an HFS+ volume which I use for TimeMachine backups.
The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.
So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time.
What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:
*
*I've tried going through options in Disk Utility
*I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.
*I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.
Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).
EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.
A: The following entry in /etc/fstab will do what you want, even on 10.5 (Leopard):
LABEL=VolumeName none ntfs noauto
If the file is not already there, just create it. Do not use /etc/fstab.hd! No reloading of diskarbitrationd needed.
If this still doesn't work for you, maybe you can find a hint in the syslog.
A: This is not directly an answer, but
The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes
I have a similar situation.
OSX remembers where you put your icons on the desktop - I've moved the icons for both of my removable drives to just above where the trash can lives.
Eject procedure becomes
*
*Hit top-left of screen with mouse to show desktop
*Drag small box around both removable drives
*Drag 2cm onto trash so they both get ejected
*Remove firewire cable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cross platform file-access tracking I'd like to be able to track file read/writes of specific program invocations. No information about the actual transactions is required, just the file names involved.
Is there a cross platform solution to this?
What are various platform specific methods?
On Linux I know there's strace/ptrace (if there are faster methods that'd be good too). I think on mac os there's ktrace.
What about Windows?
Also, it would be amazing if it would be possible to block (stall out) file accesses until some later time.
Thanks!
A: The short answer is no. There are plenty of platform specific solutions which all probably have similar interfaces, but they aren't inherently cross platform since file systems tend to be platform specific.
How do I do it well on each platform?
Again, it will depend on the platform :) For Windows, if you want to track reads/writes in flight, you might have to go with IFS. If you just want to get notified of changes, you can use ReadDirectoryChangesW or the NTFS change journal.
I'd recommend using the NTFS change journal only because it tends to be more reliable.
A: On Windows you can use the command line tool Handle or the GUI version Process Explorer to see which files a given process has open.
If you're looking for a get this information in your own program you can use the IFS kit from Microsoft to write a file system filter. The file system filter will show all file system operation for all process. File system filters are used in AV software to scan files before they are open or to scan newly created files.
A: As long as your program launches the processes you want to monitor, you can write a debugger and then you'll be notified every time a process starts or exits. When a process starts, you can inject a DLL to hook the CreateFile system calls for each individual process. The hook can then use a pipe or a socket to report file activity to the debugger.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Recommended SQL database design for tags or tagging I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?
Am I missing a best practice for tags?
A: Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Title
Table: ItemTag
Columns: ItemID, TagID
A: If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:
tagcloud: {
map: function(doc){
for(tag in doc.tags){
emit(doc.tags[tag],1)
}
}
reduce: function(keys,values){
return values.length
}
}
Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.
A: Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.
If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.
[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.
A: Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:
Use two tables:
Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID
Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title
This has some major advantages:
First it makes development much simpler: in the three-table solution for insert and update of item you have to lookup the Tag table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.
Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags for one Item, draw a Tag-Cloud and select all items for one Tag Title.
All Tags for one Item:
3-Table:
SELECT Tag.Title
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
WHERE ItemTag.ItemID = :id
2-Table:
SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id
Tag-Cloud:
3-Table:
SELECT Tag.Title, count(*)
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
GROUP BY Tag.Title
2-Table:
SELECT Tag.Title, count(*)
FROM Tag
GROUP BY Tag.Title
Items for one Tag:
3-Table:
SELECT Item.*
FROM Item
JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
JOIN Tag ON ItemTag.TagID = Tag.TagID
WHERE Tag.Title = :title
2-Table:
SELECT Item.*
FROM Item
JOIN Tag ON Item.ItemID = Tag.ItemID
WHERE Tag.Title = :title
But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.
The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.
The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.
So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)
A: I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.
Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.
A: I would suggest following design :
Item Table:
Itemid, taglist1, taglist2
this will be fast and make easy saving and retrieving the data at item level.
In parallel build another table:
Tags
tag
do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row.
Now while searching for items for a tag it will be super fast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "333"
} |
Q: Automated Web Service Testing I would like to do some integration testing of a web service from within NUnit or MBUnit. I haven't delved into this too deeply yet, but I am pretty sure I will need to spin up WebDev.WebServer.exe within the "unit test" to do this. (I know it's not really a unit test).
Yes, I can test the underlying objects the web service uses on their own (which I am), but what I am interested in testing in this cases is that the proxies are all working and handled as expected, etc.
Any advice?
A: I asked the same thing (I think ...) I got a tip on SoapUI. It looks promising but I haven't had time to test it yet.
A: I've had lots of success doing web testing with Selenium
I've used it on Linux and Windows for automated web testing of just about anything.
A: There is XMLunit (http://xmlunit.sourceforge.net/), for java and Ms.NET. it's could be interesting to check it out some specifications of WS, like wsdl:type, for example!
Cheers!
Orlando Agostinho
Lisbon/Portugal
A: I found this post and this one which have some solutions on how to start up WebDev.WebServer.exe from within a unit test. Looks like I'll need to do something along these lines.
Until I get that going, I found that what works is to simply run the web service project within VS, let the WebDev server start up that way, and then run the unit tests. Not ideal, but it's OK for now.
A: Not sure what you're asking. If you're looking to do this without some sort of webserver in between your test and the service, you're going to be disappointed.
If that's not what you're asking... maybe some clarification?
A: You may want to give Ivonna, an addon built on top of Typemock a try.
The good part about Ivonna is that you don't need to launch webserver for your test, but downside part is that it's not free.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Best way to perform dynamic subquery in MS Reporting Services? I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:
*
*Query to get a list of popular IDs
*Subquery on each item to get properties from another table
Ideally, the final report columns would look like this:
[ID] [property1] [property2] [SELECT COUNT(*)
FROM AnotherTable
WHERE ForeignID=ID]
There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.
A: I would recommend using a SubReport. You would place the SubReport in a table cell.
A: Simplest method is this:
select *,
(select count(*) from tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt
from tbl1 t1
here is a workable version (using table variables):
declare @tbl1 table
(
tbl1ID int,
prop1 varchar(1),
prop2 varchar(2)
)
declare @tbl2 table
(
tbl2ID int,
tbl1ID int
)
select *,
(select count(*) from @tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt
from @tbl1 t1
Obviously this is just a raw example - standard rules apply like don't select *, etc ...
UPDATE from Aug 21 '08 at 21:27:
@AlexCuse - Yes, totally agree on the performance.
I started to write it with the outer join, but then saw in his sample output the count and thought that was what he wanted, and the count would not return correctly if the tables are outer joined. Not to mention that joins can cause your records to be multiplied (1 entry from tbl1 that matches 2 entries in tbl2 = 2 returns) which can be unintended.
So I guess it really boils down to the specifics on what your query needs to return.
UPDATE from Aug 21 '08 at 22:07:
To answer the other parts of your question - is a VB function the way to go? No. Absolutely not. Not for something this simple.
Functions are very bad on performance, each row in the return set executes the function.
If you want to "compartmentalize" the different parts of the query you have to approach it more like a stored procedure. Build a temp table, do part of the query and insert the results into the table, then do any further queries you need and update the original temp table (or insert into more temp tables).
A: Depending on how you want the output to look, a subreport could do, or you could group on ID, property1, property2 and show the items from your other table as detail items (assuming you want to show more than just count).
Something like
select t1.ID, t1.property1, t1.property2, t2.somecol, t2.someothercol
from table t1 left join anothertable t2 on t1.ID = t2.ID
@Carlton Jenke I think you will find an outer join a better performer than the correlated subquery in the example you gave. Remember that the subquery needs to be run for each row.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java JPanel redraw issues I have a Java swing application with a panel that contains three JComboBoxes that do not draw properly.
The combox boxes just show up as the down arrow on the right side, but without the label of the currently selected value.
The boxes will redraw correctly if the window is resized either bigger or smaller by even one pixel.
All of my googling has pointed to calling revalidate() on the JPanel to fix this, but that hasn't worked for me.
Calling updateUI() on the JPanel has changed it from always displaying incorrectly to displaying incorrectly half of the time.
Has anyone else seen this and found a different way to force a redraw of the combo boxes?
A: Can you give us some more information on how you add the combo boxes to the JPanel? This is a pretty common thing to do in Swing so I doubt that it's a JVM issue but I guess anything is possible.
Specifically, I would double check to make sure you're not accessing the GUI from any background threads. In this case, maybe you're reading the choices from a DB or something and updating the JComboBox from a background thread, which is a big no-no in Swing. See SwingUtils.invokeLater().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How do I interpret 'netstat -a' output Some things look strange to me:
*
*What is the distinction between 0.0.0.0, 127.0.0.1, and [::]?
*How should each part of the foreign address be read (part1:part2)?
*What does a state Time_Wait, Close_Wait mean?
*etc.
Could someone give a quick overview of how to interpret these results?
A: What is the distinction between 0.0.0.0, 127.0.0.1, and [::]?
*
*0.0.0.0 indicates something that is listening on all interfaces on the machine.
*127.0.0.1 indicates your own machine.
*[::] is the IPv6 version of 0.0.0.0
*My machine also shows *:\* for UDP which shows that UDP connections don't really have a foreign address - they receive packets from any where. That is the nature of UDP.
How should each part of the foreign address be read (part1:part2)?
*part1 is the hostname or IP address
*part2 is the port
A: 127.0.0.1 is your loopback address also known as 'localhost' if set in your HOSTS file. See here for more info: http://en.wikipedia.org/wiki/Localhost
0.0.0.0 means that an app has bound to all ip addresses using a specific port. MS info here: http://support.microsoft.com/default.aspx?scid=kb;en-us;175952
'::' is ipv6 shorthand for ipv4 0.0.0.0.
A: Send-Q is the amount of data sent by the application, but not yet acknowledged by the other side of the socket.
Recv-Q is the amount of data received from the NIC, but not yet consumed by the application.
Both of these queues reside in kernel memory.
There are guides to help you tweak these kernel buffers, if you are so inclined. Although, you may find the default params do quite well.
A: This link has helped me a lot to interpret netstat -a
A copy from there -
TCP Connection States
Following is a brief explanation of this handshake. In this context the "client" is the peer requesting a connection and the "server" is the peer accepting a connection. Note that this notation does not reflect Client/Server relationships as an architectural principal.
Connection Establishment
The client sends a SYN message which contains the server's port and the client's Initial Sequence Number (ISN) to the server (active open).
The server sends back its own SYN and ACK (which consists of the client's ISN + 1).
The Client sends an ACK (which consists of the server's ISN + 1).
Connection Tear-down (modified three way handshake).
The client sends a FIN (active close). This is a now a half-closed connection. The client no longer sends data, but is still able to receive data from the server. Upon receiving this FIN, the server enters a passive close state.
The server sends an ACK (which is the clients FIN sequence + 1)
The server sends its own FIN.
The client sends an ACK (which is server's FIN sequence + 1). Upon receiving this ACK, the server closes the connection.
A half-closed connection can be used to terminate sending data while sill receiving data. Socket applications can call shutdown with the second argument set to 1 to enter this state.
State explanations as shown in Netstat:
State Explanation
SYN_SEND Indicates active open.
SYN_RECEIVED Server just received SYN from the client.
ESTABLISHED Client received server's SYN and session is established.
LISTEN Server is ready to accept connection.
NOTE: See documentation for listen() socket call. TCP sockets in listening state are not shown - this is a limitation of NETSTAT. For additional information, please see the following article in the Microsoft Knowledge Base:
134404 NETSTAT.EXE Does Not Show TCP Listen Sockets
FIN_WAIT_1 Indicates active close.
TIMED_WAIT Client enters this state after active close.
CLOSE_WAIT Indicates passive close. Server just received first FIN from a client.
FIN_WAIT_2 Client just received acknowledgment of its first FIN from the server.
LAST_ACK Server is in this state when it sends its own FIN.
CLOSED Server received ACK from client and connection is closed.
A: 0.0.0.0 usually refers to stuff listening on all interfaces.
127.0.0.1 = localhost (only your local interface)
I'm not sure about [::]
TIME_WAIT means both sides have agreed to close and TCP
must now wait a prescribed time before taking the connection
down.
CLOSE_WAIT means the remote system has finished sending
and your system has yet to say it's finished.
A: I understand the answer has been accepted but here is some additional information:
*
*If it says 0.0.0.0 on the Local Address column, it means that port is listening on all 'network interfaces' (i.e. your computer, your modem(s) and your network card(s)).
*If it says 127.0.0.1 on the Local Address column, it means that port is ONLY listening for connections from your PC itself, not from the Internet or network. No danger there.
*If it displays your online IP on the Local Address column, it means that port is ONLY listening for connections from the Internet.
*If it displays your local network IP on the Local Address column, it means that port is ONLY listening for connections from the local network.
*Foreign Address - The IP address and port number of the remote computer to which the socket is connected. The names that corresponds to the IP address and the port are shown unless the -n parameter is specified. If the port is not yet established, the port number is shown as an asterisk (*). (from wikipedia)
A: For those seeing [::] in their netstat output, I'm betting your machine is running IPv6; that would be equivalent to 0.0.0.0, i.e. listen on any IPv6 address.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: My VMware ESX server console volume went readonly. How can I save my VMs? Two RAID volumes, VMware kernel/console running on a RAID1, vmdks live on a RAID5. Entering a login at the console just results in SCSI errors, no password prompt. Praise be, the VMs are actually still running. We're thinking, though, that upon reboot the kernel may not start again and the VMs will be down.
We have database and disk backups of the VMs, but not backups of the vmdks themselves.
What are my options?
Our current best idea is
*
*Use VMware Converter to create live vmdks from the running VMs, as if it was a P2V migration.
*Reboot host server and run RAID diagnostics, figure out what in the "h" happened
*Attempt to start ESX again, possibly after rebuilding its RAID volume
*Possibly have to re-install ESX on its volume and re-attach VMs
*If that doesn't work, attach the "live" vmdks created in step 1 to a different VM host.
A: It was the backplane. Both drives of the RAID1 and one drive of the RAID5 were inaccessible. Incredibly, the VMware hypervisor continued to run for three days from memory with no access to its host disk, keeping the VMs it managed alive.
At step 3 above we diagnosed the hardware problem and replaced the RAID controller, cables, and backplane. After restart, we re-initialized the RAID by instructing the controller to query the drives for their configurations. Both were degraded and both were repaired successfully.
At step 4, it was not necessary to reinstall ESX; although, at bootup, it did not want to register the VMs. We had to dig up some buried management stuff to instruct the kernel to resignature the VMs. (Search VM docs for "resignature.")
I believe that our fallback plan would have worked, the VMware Converter images of the VMs that were running "orphaned" were tested and ran fine with no data loss. I highly recommend performing a VMware Converter imaging of any VM that gets into this state, after shutting down as many services as possible and getting the VM into as read-only a state as possible. Loading a vmdk either elsewhere or on the original host as a repair is usually going to be WAY faster than rebuilding a server from the ground up with backups.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Silverlight vs Flex My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development.
Most of our other development is done using .NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the .NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all .NET code. We have more .NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash.
I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers.
So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each?
A: Not to forget:
Flex is very much cross platform, as it is compiled using as Java compile which means that you can easily use Mac or Linux when developing Flex applications. I've my current cruisecontrol setup (which uses Linux) I build build Flex applications, but the development guys uses both Mac, Linux and Windows.
In my experience, java developers feels quite at home in Flex Builder since it is based on Eclipse.
A: I say let your developers try both platforms, and see which they prefer.
To answer the comments below, I just noticed that while there are lots of answers recommending Flash / Flex, the ones for Silverlight have many more up votes. It's not a matter of lying, it's just favouring what you're familiar with, not necessarily the best platform.
A: Silverlight programmer's don't know what they're missing out on, when it comes to Flex. Silverlight lacks the component model and event triggering capabilites that Flex has. Using XNA, and C#, a friend of mine has to jump through all kinds of hoops to get his Silverlight application to work. Then, it has to be handed off to a designer to get it to look half way decent.
Listen to the deepfriedbytes.com podcasts on Silverlight, and you'll hear how even a couple guys that really push Silverlight, acknowledge some of these issues. (I think, if I recall correctly, one of the guys works for Microsoft, but I could be wrong - I listened to it last week). They agree that Silverlight isn't quite ready for any huge applications, in its current state.
I would go with Flex, for a nice clean, straightforward approach - especially if you're already familiar with Flash and ActionScript 3.0. Flex makes alot more sense, in my opinion - Silverlight still has to mature.
A: At the end of the day, your developers should not be dictating your technology. This is absolutely a product decision that should be based on your users.
If you are deploying to the consumer Internet, the Flash Player or AJAX is the way to go. If you're deploying to a private LAN for a .net enterprise, you have options.
A: I think you should look at Silverlight as a long-term play, just as Microsoft seems to be doing. There's an obvious balance on when to use Silverlight vs. Flash when you're concerned about reach and install base, but here are some reasons Silverlight is a good direction to move in:
*
*Second mover advantage - Just as Microsoft built a "better Java" with .NET, they're able to look at how you'd design a RIA plugin from scratch, today. They have the advantage of knowing how people use the web today, something the inventors of Flash could never have accurately guessed. Flash can add features, but they can't realistically chuck the platform and start over.
*Developer familiarity - While Silverlight is a new model, it's not entirely unfamiliar to developers. They'll "get" the way Silverlight works a lot more quickly than they'll understand firing up a new development environment with a new scripting language and new event paradigms.
*Being rid of the timeline model in Flash - Flash was originally built for keyframe based animations, and while there are ways to abstract this away, it's at the core of how Flash works. Silverlight ditches that for an application-centric model.
*ScottGu - ScottGu is fired up about Silverlight. Nuff said.
*Cool new features - While Silverlight still has some catching up to do with Flash on some obvious features (like webcam / mic integration, or 3d / graphics acceleration), there are some slick new technologies built in to Silverlight - Deep Zoom is one example. I'm seeing more "revolutionary" technologies on the Silverlight side, while Flash seems to be in maintenance mode at this point.
A: Asa graphics designer, I've used Flash (on and off) over the last few years, and Silverlight (and its big brother WPF) over the last 1.5 years. Based on what I've heard from my team (all of whom are developers or former developers, if your .Net developers will be doing all the programming, go with Silverlight. I love Flash, but even with the OOP overhaul to ActionScript 3 in Flash 9 and up, it's still a somewhat quirky language, and going back and forth between AS3 and C# will probably drive your developers nuts :-).
For your designers, do the following:
*
*Get them a copy of Expression Blend, the GUI development tool for Silverlight/WPF.
*Blend has a somewhat steep initial learning curve, and the interface throws a ton of variables/options at you, so invest in some training, and give your designers time to get up to speed with the UI.
*Speaking of training, get a subscription to the Lynda.com video library, esp. the Lee Brimelow Expression Blend training course.
*Caveat emptor: Blend and WPF change rapidly, so sometimes you'll run into bugs in Blend that are fixed in the next beta/CTP of Blend. E.g. There was a bug in Blend 2 that prevent my storyboards (animations) from working in a recent project. I upgraded to Blend 2.5CTP, and it worked.
*Silverlight content doesn't always seem to work with the latest Beta of the Silverlight plugin, just something to keep in mind if you're testing some new feature that's only available in the latest Silverlight plugin.
*Invest in a powerful system (Quad Core, 4Gigs of RAM, etc.) Blend consumes a lot of resources, esp. when you have tons of layers. E.g. I'm working on an app with over a 100 layers(!) in the base app (and another 100+ in some of the user controls), and about 40-50 storyboards. Every few minutes, I have to restart Blend, because the UI stops responding (but doesn't freeze). Either that, or move everything you can into user controls.
A: My team used to write rich web features in Flex, and now writes them in Silverlight.
Our reasons for this switch:
*
*FlexBuilder is built on Eclipse. Eclipse is awful! Free, but bug ridden, glitch filled and slow.
*FlexBuilder is twice the price of Expression Blend, which we get for free with MSDN anyway.
*Flex is a pain to source control, it doesn't like being made to put files in one place and it doesn't play nice with other parts of your solution (we tried with SourceGear Vault and SVN).
*Flex's version of ActionScript doesn't like most SOAP implementations, in particular it has all sorts of problems with .Net WebMethod ones.
*Despite us using licensed Flex components periodically it decides that we don't have that version and adds demo-only watermarks in. The only way to remove this is to take the project to bits, reinstall Flex, reinstall the licenses and rebuild it.
*FlexBuilder does not like Vista at all.
*Silverlight acceptance is growing, once it was at the level where we could add it as a requirement for the relevant features we switched. If we were working for a web (rather than corporate) audience I'm not sure that we could have.
The rest of our project is .Net and C#, you may find all these issues less significant in a Java shop.
A: There's two questions here: Silverlight vs. Flash as platform and Silverlight vs. Flex as RIA framework.
The first question depends on your timeframe. Flash Player has over 95% reach, Silverlight has no way near that. However, Silverlight may get there, it is after all backed by Microsoft. If you aim to launch a site next week and want a huge audience, Silverlight is not an option. If you aim to launch a really cool application that everyone would want to use it's a bit different, if your app is good enough your target audience may install Silverlight just to be able to run it.
As for the second question its a matter of how easy it is to develop applications in Silverlight. Flex isn't just a set of widgets, it's a very big framework that does a lot of thing that ease the work of the developer. You could write the same applications using only the core Flash API, but it would be very much more work. Depending on what's available in Silverlight, this should be an important factor when deciding. If you can cut development time, is having two platforms worth it?
A: As Kibbee hinted at above, the argument of leveraging existing .Net developers doesn't hold much water. It is impossible to be an expert in all facets of .Net development. The platform is just too big. The same goes for Java. The only thing Silverlight has going for it from a skills perspective is that you can code in your favorite .Net language. That advantage is fairly small if you are already doing any significant web development that utilizes JavaScript since Action script is a variation. So really to convert a programmer to either Flex or Silverlight is all about learning the platform's API.
A: We went through this same issue and Flex won hands down. Our .NET developers were concerned at first, but after working so long in the pain of Ajax and JavaScript, they now LOVE and really enjoy working in Flex.
Here's a simple test for you . . . try to find at least 3 examples of real-world Silverlight applications (that aren't games, video players or gadgets). Then do the same for Flex.
A: I think Silverlight is most advantageous for companies that have .NET developers but noone with designer experience.
Skill sets will be easier to find as far as finding C# or VB developers vs finding ActionScript guru's. However there is the trade off:
Design experience is an investment not only in Designers with artistic skill, but also in the knowledge and tools provided by Adobe. You can nearly guarantee that a professional designer uses a mac and has experience with Adobe tools.
Right now the Silverlight designer tools are half baked and can be a headache. For instance Blend errors when trying to render any xaml containing an IValueConverter, this is problematic. I have no idea what the Adobe developer experience is, I'm sure it is as hairy.
So at this stage of the game it comes down to human resources:
If you have .NET experience and little invested in Design skills go Silverlight. Programming skills/tools will be transferable.
If you have Design experience and skill set go with Flex. Designer skills/tools will be transferable.
Either way both client platforms require communication with services to get data, so you will always leverage your existing programing expertise on the back end.
Paraphrased Jon's opinion from a different point of view:
I think you should look at Flex as a long-term play, just as Adobe seems to be doing. There's an obvious balance on when to use Silverlight vs. Flex when you're concerned about reach and install base, but here are more reasons Flex is a good direction to move in:
*
*Second mover advantage - Just as
Adobe built a "better Java Applet"
with Flash, they're able to look at
how you'd design a runtime from
scratch, today. They have the
advantage of knowing how people use
the web today, something the
inventors of existing client
platforms could never have
accurately guessed. .NET can add
features, but they can't
realistically chuck the platform and
start over.
*Designer familiarity - While
Flex/AIR is a new programing model,
it's not entirely unfamiliar to
designers. They'll "get" the way
Flex works a lot more quickly than
they'll understand firing up a new
design environment with new feature
poor tools and new animation
paradigms.
*Being rid of the RGB color model in
Silverlight- .NET was originally
built for windows and it is at the
core of how it works. Flex ditched a
long time ago for an design-centric
model.
*All your tools run on your mac. Nuff
said.
*Cool features - Silverlight still
has some catching up to do with
Flash on some obvious features (like
webcam / mic integration, or 3d /
graphics acceleration).
A: Although I have done work with Silverlight and am pretty excited about the ability to have apps living outside of the browser, one huge benefit of AIR is that is provides access to native drag and drop functionality. This allows you to build very user-friendly image or document uploads features (e.g. Flickr uploader). From what I heard, MS is not focusing on that kind of support yet (i.e. no plans announced).
A: We are doing both silverlight and flex, and here are developer's point of view for both.
Pros of Silverlight:
*
*Power of C#, Code Snippets, Reusing existing C# Algorithm Implementations
*Power of other languages too, Generics and Linq etc
*Power of Native execution of CLR instead of Flash's Action Script Interpretator
*One Integrated Visual Studio for All Development
*Expression Blend is really cool and more advanced editor then Flex Builder
*XAML is Search Engine Friendly
*Pretty nice state transitions and easy to define them
*Threading and Asynchronous Tasks
*Accessibility, no one knows that Microsoft always made the best accessiility features on all of its products, they always worked well with disabled people, comparing the browsers only IE supports full accessibility and Safari/firefox etc are no where closer.
Cons of Silverlight:
*
*Strictly Microsoft Platform, I know lot of people will argue but with current scenario, half of Intel Mac guys cant get silverlight 3.0 working, all PPC Mac guys cant use Silverlight 2.0 onwards, and No silverlight for Linux.
*There is mono, but not officially supported by Microsoft, it will always lag behind reverse engineering .NET and porting it on other platform, its not out of the box yet.
*Majority of components/controls are "Sealed" so its difficult to extend them and override to make new components easily.
*Bad CustomControl/UserControl architecture. E.g. you cant have XAML's root as ComboBox or any other control and let it have both design as well as code, you can create custom control but they are way too complex
*Binding requires component naming and does not support instance expressions like flex does, though two way binding is good in silverlight but you have to write long codes for multiple bindings for one math expression
e.g.
// this is possible in flex..
// but not in silverlight
<mx:TextBox id="firstName"/>
<mx:TextBox id="lastName"/>
// display full name..
<mx:Label text="{firstName.text} {lastName.text}"/>
Pros of Flex:
*
*Truely platform independent, supported on various hardware and operating systems and truely working everywhere great.
*Open Source makes it really easy to understand and extend the functionality.
*Every control/component can be extended and there are less restrictions overriding default behaviour.
*The most easy way to create new components, you can have mxml derive from any control and extend them with extensive binding
*Flex contains lots of controls and you dont need any third party library
Cons of Flex:
*
*Slow execution for iterative executions, no threads !! no async tasks !!
*Based on point 1, no great animation or graphics possible
*No generics, No other languages, No linq..
*Number class has a bug, cant store full 64 bit long value
*Eclipse is bad to design something great UI
Conclusion
*
*We use flex for data applications, those are simple form processing applications
*Silverlight for extremely rich graphics and animation
A: The problem with Silverlight, is that there's still a lot of people who don't have it installed. Also, I"m not sure how well your existing .Net developers will be able to leverage their existing skills if they are only familiar with more traditional server-side .Net coding.
What are your reasons for pushing Silverlight over Flex? If you have to ask the SOFlow community for reasons, it seems odd that you would be so willing to push it.
A: Another advantage of Flex development is that you can switch to developing desktop applications (Adobe AIR) with the same source code (and same IDE) and distribute them from web. You can check out this
for the future of Flash platform.
Update Q3/2011: Flash 11 supports low-level 3D acceleration, and there are already many frameworks and major engines (Unreal Engine 3, Unity) supporting it. The selling point for the future, however, is that AIR application will work on Windows, Mac, Android, Playbook, and iOS platforms (Linux support has been dropped). With an absolute minimum of hassle between porting between those (at least when you have Adobe CS5.5+).
Update Q2/2015: Silverlight is officially dead. Adobe AIR is alive, but not thriving - it might be useful based on your skills and tool chain. Both Microsoft and Adobe admit that HTML5 is the way to go (whether with AIR or Apache Cordova or Visual Studio).
Update Q3/2017: Haha wow, who even uses Flash anymore.
A: I think Silverlight and XAML is preferable to ActionScript, and though I'm not familiar with ActionScript IDE's, I am familiar with VS2008 and Expression Web/Blend, and they are very good development environments and getting better all the time. I would go with Silverlight, and I think the key to getting users to install the plug-in is to have a good plug-in detect page that explains what SL is and why they need it. For an example of this, go to http://memorabilia.hardrock.com/ and try it with your SL plug-in disabled.
A: I use this rule of thumb: if your company is developing internet based multimedia software, and has customers with all sorts of platforms, and you are not doing database intensive applications Flex is the definite answer, if your company develops both internet and DVD based products, less interactive but more intensive (CPU, Memory) and uses ridiculous amount of database transaction Silverlight makes more sense
A: Someone said: "Find 3 real world silverlight applications". Ok, I knew some off the top of my head but I googled it anyway. The list:
*
*2008 Beijing Olympics (stats here, 250TB of data delivered!)
*Netflix on-demand player
*AOL email client (may not be released yet)
Oh, not video players? Well that leaves the UFC application (it's a hybrid video/chat/other stuff) and the AOL email client. Silverlight excels at video and that's where it's gaining it's foothold but that doesn't mean it can't do other things. I see no reason to dismiss it just because it does video well.
Infoworld [link] said that "Silverlight has substantial technical merit and relatively good performance. It's a very capable RIA technology that's especially useful in the hands of programmers with .Net experience and designers with XAML experience." It's a good article for you to read regarding your question.
My answer: if you have a team of devs that are comfortable with .NET then Silverlight should be first on your list. If not, then it's a real tossup. I've seen articles say that Visual Studio is a superior development platform compared to what you use with Flex. But Flash is damn near ubiquitous.
Also keep in mind that Silverlight 2 uses almost no Javascript (I think none, but I'm not positive). So any avoidance of Silverlight because of JS is unfounded.
If performance matters, Silverlight wins there. I've seen my browser's CPU usage go to 100% many times and killing whatever window is running Flash always got rid of it. It's especially obvious in Chrome where you can see the process that's consuming your CPU. If your interested in Silverlight for gaming potential, look for QuakeLight, the Silverlight port of Quake. It's shaping up really well.
I really think it comes down to where your developer talent lies and what kind of application you'll be delivering. Simple game? Flash. Line of business app? Silverlight. In-between? Go with what your devs recommend.
A: If you know .NET, Silverlight 3.0 is the way to go. I'm using it and I love it. I don't have to mess with AJAX or JS BTW (I have no idea what that guy was refering to, maybe SL 1.0) For data it's mostly async WCF calls (LINQ to SQL behind WCF) or XML files or RIA Services. It let's you use most shader FX, it has styles, control templates and the native access windows/mac clipboard. I can run high def video and most processes run very well even under slow CPUs. I also enjoy the data binding, control binding and the observable collections save me a lot of time. PLUS i can use LINQ, major time saver, not to mention using Visual Studio to debug with.
I'm developing enterprise .NET applications, so I know my install base and they will install the add-in (30 seconds usually). For a front end website, you may lose some users who don't want to install silverlight or don't run Mac or Windows. You CAN have apps with SL outside of the browser with 3.0.
I may be a biased .NET guy but I've been developing so quickly I have to recommend it.
A: You seriously shouldn't use ANY of these ActiveX2.0 technologies. Neither Silverlight nor Flex...
First of all, both of them are nothing more then "distributed winforms frameworks with support for being ran in the browser", second of all they don't port well to other devices (specially true for Silverlight), thirdly they don't work good with other portions of your page. They don't work well for disabled people, etc, etc, etc. List goes on into infinity...
Adobe and Microsoft both tries to hide this fact really hard, but at the end of the day both Silverlight and Flex is nothing but ActiveX in a new wrapping...
Sure they run in sandboxes, are managed languages and all that. But it's still a big piece of BLOB being downloaded to run locally in your browser, AKA ActiveX...
A: This is an old question, history has now spoken!
Silverlight has been as good as abandoned by Microsoft, it never got a useful install base. Party due to Microsoft not committing 100% to it.
Flash (hence Flex) is still going. However more and more browsers don’t support any plug-ins, so it is only a matter of time (years) before flush goes the way of Silverlight.
Maybe one day Flex will be re-targeted to HTML5 with no plug-ins….
The iPhone was spoken, and it said the only option is Apples Way or HTML5.
A: Flash Player is available & supported officially in almost all desktop platforms (Windows, Linux, Mac) whereas Silverlight will be supported mainly in Windows.
the following article provides comparision of both the platforms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
} |
Q: Symantec Backup Exec 11d RALUS Communications Error I'm trying to do a file system backup of a RedHat Enterprise Linux v4 server using Symantec Backup Exec 11d (Rev 7170). The backup server is Windows Server 2003.
I can browse the target server to create a selection list, and when I do a test run it completes successfully.
However, when I run a real backup, the job fails immediately during the "processing" phase with the error:
e000fe30 - A communications failure has occured.
I've tried opening ports (10000, 1025-9999), etc. But no joy. Any ideas?
A: Sure sounds like firewall issues. Try stopping iptables, and running again. Also, RALUS can dump a log file - which may give some more to go on.
I use the older UNIX agent myself, which uses port 6101 IIRC - but I believe that the newer client uses tcp/10000 for control and 1024-65535 for transfer.
Last resort is to fire up a network sniffer. ;)
A: To clarify the answer, the solution was to open up the tcp ports from 1024-65535.
The iptables looked liked this:
[root@MYSERVER ~]# service iptables status
Table: filter
Chain INPUT (policy ACCEPT)
target prot opt source destination
RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0
Chain FORWARD (policy ACCEPT)
target prot opt source destination
RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain RH-Firewall-1-INPUT (2 references)
target prot opt source destination
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmp type 255
ACCEPT esp -- 0.0.0.0/0 0.0.0.0/0
ACCEPT ah -- 0.0.0.0/0 0.0.0.0/0
ACCEPT udp -- 0.0.0.0/0 224.0.0.251 udp dpt:5353
ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:631
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:80
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:443
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5801
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5802
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5804
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5901
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5902
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5904
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:9099
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:10000
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:1025
REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
I executed this command to add the new rule:
[root@MYSERVER ~]# iptables -I RH-Firewall-1-INPUT 14 -p tcp -m tcp --dport 1024:65535 -j ACCEPT
Then they looked like this:
[root@MYSERVER ~]# service iptables status
Table: filter
Chain INPUT (policy ACCEPT)
target prot opt source destination
RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0
Chain FORWARD (policy ACCEPT)
target prot opt source destination
RH-Firewall-1-INPUT all -- 0.0.0.0/0 0.0.0.0/0
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain RH-Firewall-1-INPUT (2 references)
target prot opt source destination
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmp type 255
ACCEPT esp -- 0.0.0.0/0 0.0.0.0/0
ACCEPT ah -- 0.0.0.0/0 0.0.0.0/0
ACCEPT udp -- 0.0.0.0/0 224.0.0.251 udp dpt:5353
ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:631
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:80
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:443
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5801
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5802
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5804
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpts:1025:65535
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5901
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5902
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:5904
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:9099
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:10000
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:1025
REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Save the iptables when you've verified that it works:
[root@MYSERVER ~]# service iptables save
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VBScript/IIS - How do I automatically set ASP.NET version for a particular website I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.
Ideally I would like to adsutil.vbs to update the metabase. How do I do this?
A: @Chris beat me to the punch on the ADSI way
You can do this using the aspnet_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to -
This configures ASP.NET 1.1
%windir%\microsoft.net\framework\v1.1.4322\aspnet_regiis -s W3SVC/[iisnumber]/ROOT
This configures ASP.NET 2.0
%windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -s W3SVC/[iisnumber]/ROOT
You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool.
A: I found the following script posted on Diablo Pup's blog. It uses ADSI automation.
'******************************************************************************************
' Name: SetASPDotNetVersion
' Description: Set the script mappings for the specified ASP.NET version
' Inputs: objIIS, strNewVersion
'******************************************************************************************
Sub SetASPDotNetVersion(objIIS, strNewVersion)
Dim i, ScriptMaps, arrVersions(2), thisVersion, thisScriptMap
Dim strSearchText, strReplaceText
Select Case Trim(LCase(strNewVersion))
Case "1.1"
strReplaceText = "v1.1.4322"
Case "2.0"
strReplaceText = "v2.0.50727"
Case Else
wscript.echo "WARNING: Non-supported ASP.NET version specified!"
Exit Sub
End Select
ScriptMaps = objIIS.ScriptMaps
arrVersions(0) = "v1.1.4322"
arrVersions(1) = "v2.0.50727"
'Loop through all three potential old values
For Each thisVersion in arrVersions
'Loop through all the mappings
For thisScriptMap = LBound(ScriptMaps) to UBound(ScriptMaps)
'Replace the old with the new
ScriptMaps(thisScriptMap) = Replace(ScriptMaps(thisScriptMap), thisVersion, strReplaceText)
Next
Next
objIIS.ScriptMaps = ScriptMaps
objIIS.SetInfo
wscript.echo "<-------Set ASP.NET version to " & strNewVersion & " successfully.------->"
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Nesting HTML- anchor tags Today I was working on a tab navigation for a webpage. I tried the Sliding Doors approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab).
I wanted to use a nested anchor, which didn't work because it is not allowed. Then I saw the tab- navigation at Pageflakes, which was actually working (including nested hyperlinks). Why?
A: They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS).
Here is what the html looks like:
<a class="page_tab page_tab">
<div class="page_title" title="Click to rename this page.">Click & Type Page Name</div>
<a class="delete_page" title="Click to delete this page" style="display: block;">X</a>
</a>
A: Nested links are illegal
A: Actually, the code I had pasted previously was the generated DOM, after all JS manipulation. If you don't have the Firebug extension for Firefox, you should get it now.
Edit: Deleted the old post, it was no longer useful. Firebug is, so this one is staying :)
A: I suspect that working or not working nested links might depend if your browser renders page in strict mode (e.g. XHTML DTD, application/xml+html MIMEtype), or in "quirks" mode.
A: In spite of nested tags are illegal but writing them using JS will work!, try this:
$('<a>', {
href: 'http://google.com',
html: '<a>i am nested anchor </a>I am top Anchor'
}).appendTo($('body'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Updating an auto_now DateTimeField in a parent model in Django I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:
def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
Will this work, and if you can explain it to me, why? If not, how would I accomplish this?
A: Proper version to work is: (attention to last line self.message.save())
class Message(models.Model):
updated = models.DateTimeField(auto_now = True)
...
class Attachment(models.Model):
updated = models.DateTimeField(auto_now = True)
message = models.ForeignKey(Message)
def save(self):
super(Attachment, self).save()
self.message.save()
A: You would also need to then save the message. Then it that should work.
A: DateTime fields with auto_now are automatically updated upon calling save(), so you do not need to update them manually. Django will do this work for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml? I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a System.Configuration.Configuration for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:
Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>");
MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection");
Assert.That(section != null);
However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?
A: There is actually a way I've discovered....
You need to define a new class inheriting from your original configuration section as follows:
public class MyXmlCustomConfigSection : MyCustomConfigSection
{
public MyXmlCustomConfigSection (string configXml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
DeserializeSection(reader);
}
}
You can then instantiate your ConfigurationSection object as follows:
string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);
Hope it helps someone :-)
A: I think what you're looking for is ConfigurationManager.OpenMappedExeConfiguration
It allows you to open a configuration file that you specify with a file path (wrapped inside a ExeConfigurationFileMap)
If what the other poster said is true, and you don't wish to create a whole new XML file for testing, then I'd recommend you put your Configuration edits in the Test method itself, then run your tests against the freshly changed configuration data.
A: Looking at the members of the class, I'd say the answer is probably no*. I'm not sure why you'd want to do this anyway, rather than create your own XML configuration file.
*That's no, excluding messy reflection hacks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: List of standard lengths for database fields I'm designing a database table and asking myself this question: How long should the firstname field be?
Does anyone have a list of reasonable lengths for the most common fields, such as first name, last name, and email address?
A: W3C's recommendation:
If designing a form or database that will accept names from people
with a variety of backgrounds, you should ask yourself whether you
really need to have separate fields for given name and family name.
… Bear in mind that names in some cultures can be quite a lot longer
than your own. … Avoid limiting the field size for names in your
database. In particular, do not assume that a four-character
Japanese name in UTF-8 will fit in four bytes – you are likely to
actually need 12.
https://www.w3.org/International/questions/qa-personal-names
For database fields, VARCHAR(255) is a safe default choice, unless you can actually come up with a good reason to use something else. For typical web applications, performance won't be a problem. Don't prematurely optimize.
A: Some almost-certainly correct column lengths
Min Max
Hostname 1 255
Domain Name 4 253
Email Address 7 254
Email Address [1] 3 254
Telephone Number 10 15
Telephone Number [2] 3 26
HTTP(S) URL w domain name 11 2083
URL [3] 6 2083
Postal Code [4] 2 11
IP Address (incl ipv6) 7 45
Longitude numeric 9,6
Latitude numeric 8,6
Money[5] numeric 19,4
[1] Allow local domains or TLD-only domains
[2] Allow short numbers like 911 and extensions like 16045551212x12345
[3] Allow local domains, tv:// scheme
[4] http://en.wikipedia.org/wiki/List_of_postal_codes. Use max 12 if storing dash or space
[5] http://stackoverflow.com/questions/224462/storing-money-in-a-decimal-column-what-precision-and-scale
A long rant on personal names
A personal name is either a Polynym (a name with multiple sortable components), a Mononym (a name with only one component), or a Pictonym (a name represented by a picture - this exists due to people like Prince).
A person can have multiple names, playing roles, such as LEGAL, MARITAL, MAIDEN, PREFERRED, SOBRIQUET, PSEUDONYM, etc. You might have business rules, such as "a person can only have one legal name at a time, but multiple pseudonyms at a time".
Some examples:
names: [
{
type:"POLYNYM",
role:"LEGAL",
given:"George",
middle:"Herman",
moniker:"Babe",
surname:"Ruth",
generation:"JUNIOR"
},
{
type:"MONONYM",
role:"SOBRIQUET",
mononym:"The Bambino" /* mononyms can be more than one word, but only one component */
},
{
type:"MONONYM",
role:"SOBRIQUET",
mononym:"The Sultan of Swat"
}
]
or
names: [
{
type:"POLYNYM",
role:"PREFERRED",
given:"Malcolm",
surname:"X"
},
{
type:"POLYNYM",
role:"BIRTH",
given:"Malcolm",
surname:"Little"
},
{
type:"POLYNYM",
role:"LEGAL",
given:"Malik",
surname:"El-Shabazz"
}
]
or
names:[
{
type:"POLYNYM",
role:"LEGAL",
given:"Prince",
middle:"Rogers",
surname:"Nelson"
},
{
type:"MONONYM",
role:"SOBRIQUET",
mononym:"Prince"
},
{
type:"PICTONYM",
role:"LEGAL",
url:"http://upload.wikimedia.org/wikipedia/en/thumb/a/af/Prince_logo.svg/130px-Prince_logo.svg.png"
}
]
or
names:[
{
type:"POLYNYM",
role:"LEGAL",
given:"Juan Pablo",
surname:"Fernández de Calderón",
secondarySurname:"García-Iglesias" /* hispanic people often have two surnames. it can be impolite to use the wrong one. Portuguese and Spaniards differ as to which surname is important */
}
]
Given names, middle names, surnames can be multiple words such as "Billy Bob" Thornton, or Ralph "Vaughn Williams".
A: These might be useful to someone;
youtube max channel length = 20
facebook max name length = 50
twitter max handle length = 15
email max length = 255
http://www.interoadvisory.com/2015/08/6-areas-inside-of-linkedin-with-character-limits/
A: +------------+---------------+---------------------------------+
| Field | Length (Char) | Description |
+------------+---------------+---------------------------------+
|firstname | 35 | |
|lastname | 35 | |
|email | 255 | |
|url | 60+ | According to server and browser |
|city | 45 | |
|address | 90 | |
+------------+---------------+---------------------------------+
Edit: Added some spacing
A: I wanted to find the same and the UK Government Data Standards mentioned in the accepted answer sounded ideal. However none of these seemed to exist any more - after an extended search I found it in an archive here: http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards.aspx. Need to download the zip, extract it and then open default.htm in the html folder.
A: I just queried my database with millions of customers in the USA.
*
*The maximum first name length was 46. I go with 50. (Of course, only 500 of those were over 25, and they were all cases where data imports resulted in extra junk winding up in that field.)
*Last name was similar to first name.
*Email addresses maxed out at 62
characters. Most of the longer ones
were actually lists of email
addresses separated by semicolons.
*Street address maxes out at 95
characters. The long ones were all
valid.
*Max city length was 35.
This should be a decent statistical spread for people in the US. If you have localization to consider, the numbers could vary significantly.
A: UK Government Data Standards Catalogue details the UK standards for this kind of thing.
It suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name, and 255 characters for an email address. Amongst other things..
A: I would say to err on the high side. Since you'll probably be using varchar, any extra space you allow won't actually use up any extra space unless somebody needs it. I would say for names (first or last), go at least 50 chars, and for email address, make it at least 128. There are some really long email addresses out there.
Another thing I like to do is go to Lipsum.com and ask it to generate some text. That way you can get a good idea of just what 100 bytes looks like.
A: I pretty much always use a power of 2 unless there is a good reason not to, such as a customer facing interface where some other number has special meaning to the customer.
If you stick to powers of 2 it keeps you within a limited set of common sizes, which itself is a good thing, and it makes it easier to guess the size of unknown objects you may encounter. I see a fair number of other people doing this, and there is something aesthetically pleasing about it. It generally gives me a good feeling when I see this, it means the designer was thinking like an engineer or mathematician. Though I'd probably be concerned if only prime numbers were used. :)
A: Just looking though my email archives, there are a number of pretty long "first" names (of course what is meant by first is variable by culture). One example is Krishnamurthy - which is 13 letters long. A good guess might be 20 to 25 letters based on this. Email should be much longer since you might have [email protected]. Also, gmail and some other mail programs allow you to use [email protected] where "sometag" is anything you want to put there so that you can use it to sort incoming emails. I frequently run into web forms that don't allow me to put in my full email address without considering any tags. So, if you need a fixed email field maybe something like [email protected] in characters for a total of 90 characters (if I did my math right!).
A: I usually go with:
Firstname: 30 chars
Lastname: 30 chars
Email: 50 chars
Address: 200 chars
If I am concerned about long fields for the names, I might sometimes go with 50 for the name fields too, since storage space is rarely an issue these days.
A: If you need to consider localisation (for those of us outside the US!) and it's possible in your environment, I'd suggest:
Define data types for each component of the name - NOTE: some cultures have more than two names! Then have a type for the full name,
Then localisation becomes simple (as far as names are concerned).
The same applies to addresses, BTW - different formats!
A: it is varchar right? So it then doesn't matter if you use 50 or 25, better be safe and use 50, that said I believe the longest I have seen is about 19 or so. Last names are longer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "474"
} |
Q: Determine Loaded Assemblies How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.
It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.
A: PowerShell Version:
[System.AppDomain]::CurrentDomain.GetAssemblies()
A: Either that, or System.Reflection.Assembly.GetLoadedModules().
Note that AppDomain.GetAssemblies will only iterate assemblies in the current AppDomain. It's possible for an application to have more than one AppDomain, so that may or may not do what you want.
A: using System;
using System.Reflection;
using System.Windows.Forms;
public class MyAppDomain
{
public static void Main(string[] args)
{
AppDomain ad = AppDomain.CurrentDomain;
Assembly[] loadedAssemblies = ad.GetAssemblies();
Console.WriteLine("Here are the assemblies loaded in this appdomain\n");
foreach(Assembly a in loadedAssemblies)
{
Console.WriteLine(a.FullName);
}
}
}
A: Looks like AppDomain.CurrentDomain.GetAssemblies(); will do the trick :)
A: For all DLLs including unmanaged, you could pinvoke EnumProcessModules to get the module handles and then use GetModuleFileName for each handle to get the name.
See http://pinvoke.net/default.aspx/psapi.EnumProcessModules and http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx (pinvoke.net does not have the signature for this but it's easy to figure out).
For 64 bit you need to use EnumProcessModulesEx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Storing logged in user details When creating a web application, and lets say you have a User object denoting a single user, what do you think is the best way to store that the user has logged in?
Two ways I've thought about have been:
*
*Stored the user database id in a session variable
*Stored the entire user object in a session variable
Any better suggestions, any issues with using the above ways? Perhaps security issues or memory issues, etc, etc.
A: For security's sake, I would generate (either a GUID or cryptographically safe RNG) a session ID and have a table that just maps session IDs to user IDs. Then, you just store the session ID in their cookies, and have it act as a proxy for the user id.
|Session |UserID |
|--------+-------|
|a1d4e...+ 12345 |
|--------+-------|
|c64b2...+ 23456 |
|--------+-------|
With this, no one can impersonate another user by guessing their ID. It also lets you limit users' sessions so they have to log in every so often (two weeks is the usual). And if you want to store other data about their session, you can just add it to this table.
A: Just remember that if you store all the user's attributes (this extends to permissions) in the session, then any changes to the user won't take effect until they login again.
Personally, I store the name and id for quick reference, and fetch the rest when I need to.
A: Storing the ID is the best practice in most cases. One important reason for this is scalability. If you store the user object (or any entities from the database, instead of just their IDs), you are going to run into problems expanding the number of servers serving your site. For more information, google for "shared nothing architecture".
A: I recommend storing the id rather than the object. The downside is that you have to hit the database every time you want to get that user's information. However, unless every millisecond counts in your page, the performance shouldn't be an issue. Here are two advantages:
*
*If the user's information changes somehow, then you won't be storing out-of-date information in your session. For example, if a user is granted extra privileges by an admin, then those will be immediately available without the user needing to log out and then log back in.
*If your session information is stored on the hard drive, then you can only store serializable data. So if your User object ever contains anything like a database connection, open socket, file descriptor, etc then this will not be stored properly and may not be cleaned up properly either.
In most cases these concerns won't be an issue and either approach would be fine.
A: I think that it depends on what platform you are using. If you are using ASP.net, then I would definitely take a look at the FormsAuthentication class and all of the built-in (and extendable) functionality there that you can use for storing your logged-in user settings.
A: I would store a hashed value of the user id and the session id and then match that up in a sessions table in the database. That way it will be harder to spoof the session data. Could do i check on the IP too as an extra check.
Not sure i would want to rely on a userid being stored in a session variable and trust that it was that user as it could be altered fairly easily and gain access as another member
A: I store the user in the session, usually. The can't-change-until login problem can be solved by replacing the object in the session with a new copy after you've made changes.
A: Our user object is fairly lightweight so we opted to store it in a session variable. Not sure if that's most efficient but so far it's working very nicely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Cannot Add a Sql Server Login When I try to create a SQL Server Login by saying
CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS;
I get this error
The server principal 'ourdomain\SQLAccessGroup' already exists.
However, when I try this code
DROP LOGIN [ourdomain\SQLAccessGroup]
I get this error
Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission.
The user that I am executing this code as is a sysadmin. Additionally, the user ourdomain\SQLAccessGroup does not show up in this query
select * from sys.server_principals
Does anyone have any ideas?
A: We are still struggling to understand the HOW of this issue, but it seems that [ourdomain\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation). We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game.
Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error:
The login already has an account under a different user name.
So, I started to examine each DB user and was able to figure out the culprit. I eventually tracked it down and was able to rename the user and login so that the CRM install would work. I wonder if I can bill them $165.00 an hour for my time... :-)
A: is this when you are restoring from a backup or something? I've found that the following works for me in situations when I'm having problems with user accounts in sql
EXEC sp_change_users_login ‘Auto_Fix’, ‘user_in_here’
A: This happened to me when I installed SQL Server using a Windows username and then I renamed the computer name and the Windows username from Windows. SQL server still has the old "Computername\Username" in its node of Server->Security->Logins.
The solution is to go to Server->Security->Logins and right-click -> rename the old Windows user and use the new MachineName\Username.
A: I faced similar issue and i believe the issue was as a result of trying to recreate a login account after deleting an existing one with same name.
Just go through the various databases on the server using SQL Studio.
Example steps:
DBName ->Security->users
at this level for each of the databases, you may see the name of the user account there. Delete all occurrence in each Database as well as its occurrence in the top level Security settings at
Security->Logins
When done, try recreating the login account again and you should be fine.
A: I had the same story as Shadi.
On the top I can add that it can be also done by query:
ALTER LOGIN "oldname\RMS" WITH name="currentname\RMS"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Changing Ctrl + Tab behavior for moving between documents in Visual Studio Is it possible to change how Ctrl + Tab and Shift + Ctrl + Tab work in Visual Studio? I have disabled the popup navigator window, because I only want to switch between items in the tab control. My problem is the inconsistency of what switching to the next and previous document do.
Every other program that uses a tab control for open document I have seen uses Ctrl + Tab to move from left to right and Shift + Ctrl + Tab to go right to left. Visual Studio breaks this with its jump to the last tab selected. You can never know what document you will end up on, and it is never the same way twice.
It is very counterintuitive. Is this a subtle way to encourage everyone to only ever have two document open at once?
Let's say I have a few files open. I am working in one, and I need to see what is in the next tab to the right. In every other single application on the face of the Earth, Ctrl + Tab will get me there. But in Visual Studio, I have no idea which of the other tabs it will take me to. If I only ever have two documents open, this works great. As soon as you go to three or more, all bets are off as to what tab Visual Studio has decided to send you to.
The problem with this is that I shouldn't have to think about the tool, it should fade into the background, and I should be thinking about the task. The current tab behavior keeps pulling me out of the task and makes me have to pay attention to the tool.
A: Navigate to the blog post Visual Studio Tab Un-stupidifier Macro and make use of the macro. After you apply the macro to your installation of Visual Studio you can bind your favorite keyboard shortcuts to them. Also notice the registry fix in the comments for not displaying the macro balloon since they might get annoying after a while.
A: After a couple of hours of searching I found a solution how to switch between open documents using CTRL+TAB which move from left to right and SHIFT+ CTRL+ TAB to go right to left.
In short you need to copy and paste this macro:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module TabCtrl
Public Sub TabForward()
Dim i As Integer
Dim activateNext As Boolean = False
For i = 1 To DTE.Windows.Count
If DTE.Windows().Item(i).Kind = "Document" Then
If activateNext Then
DTE.Windows().Item(i).Activate()
GoTo done
End If
If DTE.Windows().Item(i) Is DTE.ActiveWindow Then
activateNext = True
End If
End If
Next
' Was the last window... go back to the first
If activateNext Then
For i = 1 To DTE.Windows.Count
If DTE.Windows().Item(i).Kind = "Document" Then
DTE.Windows().Item(i).Activate()
GoTo done
End If
Next
End If
done:
End Sub
Public Sub TabBackward()
Dim i As Integer
Dim activateNext As Boolean = False
For i = DTE.Windows.Count To 1 Step -1
If DTE.Windows().Item(i).Kind = "Document" Then
If activateNext Then
DTE.Windows().Item(i).Activate()
GoTo done
End If
If DTE.Windows().Item(i) Is DTE.ActiveWindow Then
activateNext = True
End If
End If
Next
' Was the first window... go back to the last
If activateNext Then
For i = DTE.Windows.Count To 1 Step -1
If DTE.Windows().Item(i).Kind = "Document" Then
DTE.Windows().Item(i).Activate()
GoTo done
End If
Next
End If
done:
End Sub
End Module
The macro comes from: www.mrspeaker.net/2006/10/12/tab-un-stupidifier/
If you never add a macro to Visual Studio there is a very useful link how to do it.
A: Ctl + Alt + PgUp or PgDn shortcuts worked to toggle next/prev tab out of the box for me...
A: Visual Studio 2010 has, built in, a way to solve this.
By default, Ctrl+Tab and Ctrl+Shift+Tab are assigned to Window.[Previous/Next]..Document, but you can, through
Tools -> Options -> Environment -> Keyboard,
remove those key assignments and reassign them to Window.[Next/Previous]Tab to add the desired behavior.
A: The philosophy of the Visual Studio tab order is very counterintuitive since the order of the displayed tabs differs from the tab-switching logic, rendering the ordering of the tabs completely useless.
So until a better solution arises, change the window layout (in Environment->General) from tabbed-documents to multiple-documents; it will not change the behaviour, but it reduces the confusion caused by the tabs.
That way you will also find the DocumentWindowNav more useful!
A: I guess you want what VSS calls Next(Previous)DocumentWindow. By default, it's on Ctrl(-Shift)-F6 on my VSS 8. On Ctrl(-Shift)-Tab they have Next(Previous)DocumentWindowNav. You can change key assignments via Tools/Options/Keyboard.
A: I'm 100% in agreement with Jeff.
I had worked on Borland C++ Builder for several years and one of the features I miss most is the 'correct' document tabbing order with Ctrl-Tab. As Jeff said, "The current tab behavior keeps pulling me out of the task and makes me have to pay attention to the tool " is exactly how I feels about this, and I'm very much surprised by the fact that there aren't many people complaining about this.
I think Ctrl-F6 - NextDocumentWindowNav - navigates documents based on the document's last-activated time. This behavior is a lot like how MDI applications used to behave in old days.
With this taken this into account, I usually use Ctrl+F6 to switch between 2 documents (which is pretty handy in switching between .cpp and .h files when working on c++ project) even when there are more than 2 currently opened documents. For example, if you have 10 documents open (Tab1, Tab2, Tab3, ...., Tab10), I click on Tab1 and then Tab2. When I do Ctrl+F6 and release keys, I'll jump to Tab1. Pressing Ctrl+F6 again will take me back to Tab2.
A: it can be changed, at least in VS 2012 (I think it should work for 2010 too).
1) TOOLS > Options > Environment > Keyboard
(Yes TOOLS, its VS2012 !) Now three shortcuts to check.
2) Window.NextDocumentWindow - you can reach there quickly by typing on the search pane on top. Now this is your enemy. Remove it if you dont like it. Change it to something else (and dont forget the Assign button) if want to have your own, but do remember that shortcut whatever it is in the end. It will come handy later.
(I mean this is the shortcut that remembers your last tab)
3) Now look for Window.NextDocumentWindowNav - this is the same as above but shows a preview of opened tabs (you can navigate to other windows too quickly with this pop-up). I never found this helpful though. Do all that mentioned in step 2 (don't forget to remember).
4) Window.NextTab - your magic potion. This would let you cycle through tabs in the forward order. May be you want CTRL+TAB? Again step 2 and remember.
5) Now place cursor in the Press shortcut keys: textbox (doesn't matter what is selected currently, you're not going to Assign this time), and type first of the three (or two or one) shortcuts.
You'll see Shortcut currently used by: listed. Ensure that you have no duplicate entry for the shortcut. In the pic, there are no duplicate entries. In case you have (a rarity), say X, then go to X, and remove the shortcut. Repeat this step for other shortcuts as well.
6) Now repeat 1-5 for Previous shortcuts as well (preferably adding Shift).
7) Bonus: Select VS2005 mapping scheme (at the top of the same box), so now you get F2 for Rename members and not CTRL+R+R, and F7 for View Code and not CTRL+ALT+0.
I'm of the opinion VS has got it right by default. I find it extremely useful that VS remembers what I used last, and makes switching easier, much like what the OS itself does (on ALT+TAB). My browser does the same too by default (Opera), though I know Firefox behaves differently.
A: In registry branch:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0
add DWORD named "UseMRUDocOrdering" with value of 1.
It will order documents so most recently used are placed on the left. It's not perfect but better than the default misbehaviour.
A: In Visual Studio 2015 (as well as previous versions of VS, but you must install Productivity Power Tools if you're using VS2013 or below), there are two new commands in Visual Studio:
Window.NextTab and
Window.PreviousTab
Just go remap them from Ctrl+Alt+PageUp/Ctrl+Alt+PageDown to Ctrl+Tab/Ctrl+Shift+Tab in:
Menu Tools -> Options -> Environment -> Keyboard
Note: In earlier versions such as Visual Studio 2010, Window.NextTab and Window.PreviousTab were named Window.NextDocumentWellTab and
Window.PreviousDocumentWellTab.
A: In Visual Studio 2012 or later (2013, 2015, 2017...):
*
*Browse the menu Tools / Options / Environment / Keyboard.
*Search for the command 'Window.NextTab', set the shortcut to Ctrl+Tab
*Search for the command 'Window.PreviousTab', set the shortcut to Ctrl+Shift+Tab
A: Updated to VS 2017+, where, according to @J-Bob's comment under @thepaulpage's answer, (emphasis added):
Looks like the commands have changed again. It's now 2017 and the keyboard shortcuts are called Open Next Editor and Open Previous Editor. You don't need any extensions for this.
You can find the options under Settings, which can be accessed via the gear symbol in the lower left, or by the [Ctrl]+, command.
A: I don't use Visual Studio (yes, really, I don't use it), but AutoHotkey can remap any hotkey globally or in a particular application:
#IfWinActive Microsoft Excel (application specific remapping)
; Printing area in Excel (@ Ctrl+Alt+A)
^!a::
Send !ade
return
#IfWinActive
$f4::
; Closes the active window (make double tapping F4 works like ALT+F4)
if f4_cnt > 0
{
f4_cnt += 1
return
}
f4_cnt = 1
SetTimer, f4_Handler, 250
return
f4_Handler:
SetTimer, f4_Handler, off
if (f4_cnt >= 2) ; Pressed more than two times
{
SendInput !{f4}
} else {
; Resend f4 to the application
Send {f4}
}
f4_cnt = 0
return
These are two remappings of my main AutoHotKey script. I think it's an excellent tool for this type of tasks.
A: I feel the top answer at the moment is outdated. In Visual Studio 2021 (v1.56), you do not need to install any extensions or mess around with any configuration files. You simply need to do the following steps:
*
*Click the gear icon in the bottom-left.
*Select 'Keyboard Shortcuts'.
*Search for 'workbench.action.previousEditor' and 'workbench.action.nextEditor' and edit their keybindings by clicking the pencil icon on the left side of the row.
If you do change to 'Ctrl+tab' or any other shortcut that is already in use by another command, it will let you know and give you the option to change those. I personally changed them to 'Ctrl+PgUp' and 'Ctrl+PgDn' so it was just a straight swap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "324"
} |
Q: "using" namespace equivalent in ASP.NET markup When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following:
<%#((MyType)Container.DataItem).PropertyOfMyType%>
The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified.
<%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%>
Is there any kind of using directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?
A: What you're looking for is the @Import page directive.
A: I believe you can add something like:
<%@ Import Namespace="RootNamespace.SubNamespace1" %>
At the top of the page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Is there any way to configure windows to not change the focus? I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)
Do you know if there's some setting I could touch for this not to happen?
A: Not that I know of. This has been a plague of Windows versions for quite some time.
A: Actually Windows XP tries to avoid that. Of course some programs found a way to circumvented that. Microsoft Powertoy TweakUI has a way to turn the option on again in case it was turned off. You could also edit the registry yourself using the following information.
A: It suppose to be a registry change that helps with this type of situations (mentioned in this Coding Horror post about the subject of "focus stealing"). I try it, it doesn't work with all popups but helps with some of them, causing the offending application to flash in the taskbar instead of gain focus.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Most efficient way to concatenate strings? What's the most efficient way to concatenate strings?
A: There are 6 types of string concatenations:
*
*Using the plus (+) symbol.
*Using string.Concat().
*Using string.Join().
*Using string.Format().
*Using string.Append().
*Using StringBuilder.
In an experiment, it has been proved that string.Concat() is the best way to approach if the words are less than 1000(approximately) and if the words are more than 1000 then StringBuilder should be used.
For more information, check this site.
string.Join() vs string.Concat()
The string.Concat method here is equivalent to the string.Join method invocation with an empty separator. Appending an empty string is fast, but not doing so is even faster, so the string.Concat method would be superior here.
A: From this MSDN article:
There is some overhead associated with
creating a StringBuilder object, both
in time and memory. On a machine with
fast memory, a StringBuilder becomes
worthwhile if you're doing about five
operations. As a rule of thumb, I
would say 10 or more string operations
is a justification for the overhead on
any machine, even a slower one.
So if you trust MSDN go with StringBuilder if you have to do more than 10 strings operations/concatenations - otherwise simple string concat with '+' is fine.
A: From Chinh Do - StringBuilder is not always faster:
Rules of Thumb
*
*When concatenating three dynamic string values or less, use traditional string concatenation.
*When concatenating more than three dynamic string values, use StringBuilder.
*When building a big string from several string literals, use either the @ string literal or the inline + operator.
Most of the time StringBuilder is your best bet, but there are cases as shown in that post that you should at least think about each situation.
A: Try this 2 pieces of code and you will find the solution.
static void Main(string[] args)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < 10000000; i++)
{
s.Append( i.ToString());
}
Console.Write("End");
Console.Read();
}
Vs
static void Main(string[] args)
{
string s = "";
for (int i = 0; i < 10000000; i++)
{
s += i.ToString();
}
Console.Write("End");
Console.Read();
}
You will find that 1st code will end really quick and the memory will be in a good amount.
The second code maybe the memory will be ok, but it will take longer... much longer.
So if you have an application for a lot of users and you need speed, use the 1st. If you have an app for a short term one user app, maybe you can use both or the 2nd will be more "natural" for developers.
Cheers.
A: It's also important to point it out that you should use the + operator if you are concatenating string literals.
When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs.
How to: Concatenate Multiple Strings (C# Programming Guide)
A: Adding to the other answers, please keep in mind that StringBuilder can be told an initial amount of memory to allocate.
The capacity parameter defines the maximum number of characters that can be stored in the memory allocated by the current instance. Its value is assigned to the Capacity property. If the number of characters to be stored in the current instance exceeds this capacity value, the StringBuilder object allocates additional memory to store them.
If capacity is zero, the implementation-specific default capacity is used.
Repeatedly appending to a StringBuilder that hasn't been pre-allocated can result in a lot of unnecessary allocations just like repeatedly concatenating regular strings.
If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the Capacity property. Especially when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.
If you can't make any kind of guess about the size, you're probably writing a utility function which should have its own optional argument for controlling pre-allocation.
A: Following may be one more alternate solution to concatenate multiple strings.
String str1 = "sometext";
string str2 = "some other text";
string afterConcate = $"{str1}{str2}";
string interpolation
A: Another solution:
inside the loop, use List instead of string.
List<string> lst= new List<string>();
for(int i=0; i<100000; i++){
...........
lst.Add(...);
}
return String.Join("", lst.ToArray());;
it is very very fast.
A: Rico Mariani, the .NET Performance guru, had an article on this very subject. It's not as simple as one might suspect. The basic advice is this:
If your pattern looks like:
x = f1(...) + f2(...) + f3(...) + f4(...)
that's one concat and it's zippy, StringBuilder probably won't help.
If your pattern looks like:
if (...) x += f1(...)
if (...) x += f2(...)
if (...) x += f3(...)
if (...) x += f4(...)
then you probably want StringBuilder.
Yet another article to support this claim comes from Eric Lippert where he describes the optimizations performed on one line + concatenations in a detailed manner.
A: The most efficient is to use StringBuilder, like so:
StringBuilder sb = new StringBuilder();
sb.Append("string1");
sb.Append("string2");
...etc...
String strResult = sb.ToString();
@jonezy: String.Concat is fine if you have a couple of small things. But if you're concatenating megabytes of data, your program will likely tank.
A: System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have concept of a mutable string where a variety of operations can be performed without allocation separate memory location for the modified string.
A: I've tested all the methods in this page and at the end I've developed my solution that is the fastest and less memory expensive.
Note: tested in Framework 4.8
[MemoryDiagnoser]
public class StringConcatSimple
{
private string
title = "Mr.", firstName = "David", middleName = "Patrick", lastName = "Callan";
[Benchmark]
public string FastConcat()
{
return FastConcat(
title, " ",
firstName, " ",
middleName, " ",
lastName);
}
[Benchmark]
public string StringBuilder()
{
var stringBuilder =
new StringBuilder();
return stringBuilder
.Append(title).Append(' ')
.Append(firstName).Append(' ')
.Append(middleName).Append(' ')
.Append(lastName).ToString();
}
[Benchmark]
public string StringBuilderExact24()
{
var stringBuilder =
new StringBuilder(24);
return stringBuilder
.Append(title).Append(' ')
.Append(firstName).Append(' ')
.Append(middleName).Append(' ')
.Append(lastName).ToString();
}
[Benchmark]
public string StringBuilderEstimate100()
{
var stringBuilder =
new StringBuilder(100);
return stringBuilder
.Append(title).Append(' ')
.Append(firstName).Append(' ')
.Append(middleName).Append(' ')
.Append(lastName).ToString();
}
[Benchmark]
public string StringPlus()
{
return title + ' ' + firstName + ' ' +
middleName + ' ' + lastName;
}
[Benchmark]
public string StringFormat()
{
return string.Format("{0} {1} {2} {3}",
title, firstName, middleName, lastName);
}
[Benchmark]
public string StringInterpolation()
{
return
$"{title} {firstName} {middleName} {lastName}";
}
[Benchmark]
public string StringJoin()
{
return string.Join(" ", title, firstName,
middleName, lastName);
}
[Benchmark]
public string StringConcat()
{
return string.
Concat(new String[]
{ title, " ", firstName, " ",
middleName, " ", lastName });
}
}
Yes, it use unsafe
public static unsafe string FastConcat(string str1, string str2, string str3, string str4, string str5, string str6, string str7)
{
var capacity = 0;
var str1Length = 0;
var str2Length = 0;
var str3Length = 0;
var str4Length = 0;
var str5Length = 0;
var str6Length = 0;
var str7Length = 0;
if (str1 != null)
{
str1Length = str1.Length;
capacity = str1Length;
}
if (str2 != null)
{
str2Length = str2.Length;
capacity += str2Length;
}
if (str3 != null)
{
str3Length = str3.Length;
capacity += str3Length;
}
if (str4 != null)
{
str4Length = str4.Length;
capacity += str4Length;
}
if (str5 != null)
{
str5Length = str5.Length;
capacity += str5Length;
}
if (str6 != null)
{
str6Length = str6.Length;
capacity += str6Length;
}
if (str7 != null)
{
str7Length = str7.Length;
capacity += str7Length;
}
string result = new string(' ', capacity);
fixed (char* dest = result)
{
var x = dest;
if (str1Length > 0)
{
fixed (char* src = str1)
{
Unsafe.CopyBlock(x, src, (uint)str1Length * 2);
x += str1Length;
}
}
if (str2Length > 0)
{
fixed (char* src = str2)
{
Unsafe.CopyBlock(x, src, (uint)str2Length * 2);
x += str2Length;
}
}
if (str3Length > 0)
{
fixed (char* src = str3)
{
Unsafe.CopyBlock(x, src, (uint)str3Length * 2);
x += str3Length;
}
}
if (str4Length > 0)
{
fixed (char* src = str4)
{
Unsafe.CopyBlock(x, src, (uint)str4Length * 2);
x += str4Length;
}
}
if (str5Length > 0)
{
fixed (char* src = str5)
{
Unsafe.CopyBlock(x, src, (uint)str5Length * 2);
x += str5Length;
}
}
if (str6Length > 0)
{
fixed (char* src = str6)
{
Unsafe.CopyBlock(x, src, (uint)str6Length * 2);
x += str6Length;
}
}
if (str7Length > 0)
{
fixed (char* src = str7)
{
Unsafe.CopyBlock(x, src, (uint)str7Length * 2);
}
}
}
return result;
}
You can edit the method and adapt it to your case. For example you can make it something like
public static unsafe string FastConcat(string str1, string str2, string str3 = null, string str4 = null, string str5 = null, string str6 = null, string str7 = null)
A: The StringBuilder.Append() method is much better than using the + operator. But I've found that, when executing 1000 concatenations or less, String.Join() is even more efficient than StringBuilder.
StringBuilder sb = new StringBuilder();
sb.Append(someString);
The only problem with String.Join is that you have to concatenate the strings with a common delimiter.
Edit: as @ryanversaw pointed out, you can make the delimiter string.Empty.
string key = String.Join("_", new String[]
{ "Customers_Contacts", customerID, database, SessionID });
A: If you're operating in a loop, StringBuilder is probably the way to go; it saves you the overhead of creating new strings regularly. In code that'll only run once, though, String.Concat is probably fine.
However, Rico Mariani (.NET optimization guru) made up a quiz in which he stated at the end that, in most cases, he recommends String.Format.
A: Here is the fastest method I've evolved over a decade for my large-scale NLP app. I have variations for IEnumerable<T> and other input types, with and without separators of different types (Char, String), but here I show the simple case of concatenating all strings in an array into a single string, with no separator. Latest version here is developed and unit-tested on C# 7 and .NET 4.7.
There are two keys to higher performance; the first is to pre-compute the exact total size required. This step is trivial when the input is an array as shown here. For handling IEnumerable<T> instead, it is worth first gathering the strings into a temporary array for computing that total (The array is required to avoid calling ToString() more than once per element since technically, given the possibility of side-effects, doing so could change the expected semantics of a 'string join' operation).
Next, given the total allocation size of the final string, the biggest boost in performance is gained by building the result string in-place. Doing this requires the (perhaps controversial) technique of temporarily suspending the immutability of a new String which is initially allocated full of zeros. Any such controversy aside, however...
...note that this is the only bulk-concatenation solution on this page which entirely avoids an extra round of allocation and copying by the String constructor.
Complete code:
/// <summary>
/// Concatenate the strings in 'rg', none of which may be null, into a single String.
/// </summary>
public static unsafe String StringJoin(this String[] rg)
{
int i;
if (rg == null || (i = rg.Length) == 0)
return String.Empty;
if (i == 1)
return rg[0];
String s, t;
int cch = 0;
do
cch += rg[--i].Length;
while (i > 0);
if (cch == 0)
return String.Empty;
i = rg.Length;
fixed (Char* _p = (s = new String(default(Char), cch)))
{
Char* pDst = _p + cch;
do
if ((t = rg[--i]).Length > 0)
fixed (Char* pSrc = t)
memcpy(pDst -= t.Length, pSrc, (UIntPtr)(t.Length << 1));
while (pDst > _p);
}
return s;
}
[DllImport("MSVCR120_CLR0400", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe void* memcpy(void* dest, void* src, UIntPtr cb);
I should mention that this code has a slight modification from what I use myself. In the original, I call the cpblk IL instruction from C# to do the actual copying. For simplicity and portability in the code here, I replaced that with P/Invoke memcpy instead, as you can see. For highest performance on x64 (but maybe not x86) you may want to use the cpblk method instead.
A: For just two strings, you definitely do not want to use StringBuilder. There is some threshold above which the StringBuilder overhead is less than the overhead of allocating multiple strings.
So, for more that 2-3 strings, use DannySmurf's code. Otherwise, just use the + operator.
A: It really depends on your usage pattern.
A detailed benchmark between string.Join, string,Concat and string.Format can be found here: String.Format Isn't Suitable for Intensive Logging
(This is actually the same answer I gave to this question)
A: It would depend on the code.
StringBuilder is more efficient generally, but if you're only concatenating a few strings and doing it all in one line, code optimizations will likely take care of it for you. It's important to think about how the code looks too: for larger sets StringBuilder will make it easier to read, for small ones StringBuilder will just add needless clutter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "339"
} |
Q: Do you use MDA/MDD/MDSD, any kind of model-driven approach? Will it be the future? Programming languages had several (r)evolutionary steps in their history. Some people argue that model-driven approaches will be The Next Big Thing. There are tools like openArchitectureWare, AndroMDA, Sculptor/Fornax Platform etc. that promise incredible productivity boosts. However, I made the experience that it is either rather easy in the beginning to get started but as well to get stuck at some point when you try something that was unanticipated or pretty hard to find enough information that tells you how to start your project because there may be a lot of things to consider.
I think an important insight to get anything out of model-driven something is to understand that the model is not necessarily a set of nice pictures or tree model or UML, but may as well be a textual description (e.g. a state machine, business rules etc.).
What do you think and what does your experience tell you? Is there a future for model-driven development (or whatever you may want to call it)?
Update: There does not seem to be a lot of interest in this topic. Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.
A: Disclaimer: I am a developer of business applications. The following view is certainly shaped by my experiences in trenches of enterprise IT. I am aware, that there are other domains of software development. Especially in industrial and/or embedded systems development the world might look different.
I think MDSD is still too much tied to code generation.
Code generation is only useful, when your code contains a lot of noise and/or is very repetitive. In other words, when your code can not mainly focus on the essential complexity, but is polluted with accidental complexity.
In my opinion the trend in current platforms and frameworks is exactly to remove accidental complexity and letting the application code focus on essential complexity.
So these new platforms/frameworks take a lot of the wind out of the sails of the MDSD movement.
DSLs (textual ones) are another trend that tries to enable the sole focus on essential complexity. While DSLs can be used as source for code generation, they are not primarily tied to code generation. DSLs (especially internal DSLs) basically let it open to be interpreted/executed at runtime. [runtime code generation is somewhere in between].
So even if DSLs are often mentioned together with MDSD, I think they are really an alternative to MDSD. And given the current hype, they also take the momentum out of the MDSD movement.
If you have reached the goal of ultimately removing accidental complexity out of your code (I know this is fictitious), then you have arrived at a textual model of your business problem. This cannot be further simplified!
Nice boxes and diagrams do not offer another simplification or elevation of the abstraction level! They may be good for visualization, but even that is questionable. A picture is not always the best representation to grasp complexity!
Further more, the current state of the tooling involved in MDSD adds another level of accidental complexity (think: synchronization, diffing/merging, refactoring ...) which basically nullifies the ultimate goal of simplification!
Look at the following ActiveRecord model, as an illustration of my theory:
class Firm < ActiveRecord::Base
has_many :clients
has_one :account
belongs_to :conglomorate
end
I dont think that this can be any more simplified. Also any graphical representation with boxes and lines would be no simplification, and would not offer any more convenience (think about layouting, refactoring, searching, diffing ...).
A: Model Driven development has been around for a very long time.
The most succesfull of the early attempts was James Martins Integrated Engineering Facility" which is still around and marketed by CA under the seriously uncool "Coolgen" brand name.
So why didnt it take over the world if it was so good?
Well these tools are good at making the simple stuff simpler, but, they dont make the hard stuff any easier, and in many cases make the hard stuff harder!
You can spend hours trying to persuade a graphic 4GL modeling language to "do the right thing" when you know that coding the right thing in Java/C/SQL or whatever would be trivial.
A: I think perhaps there isn't a definitive answer - hence the lack of "interest" in this question.
But I have personally had mixed experience with MDA. The only time it was good experience was with great tools - I used to use TogetherSoft (I believe they somehow ended up at borland) - they were one of the first to introduce editing which was not "code generation" but actually editing the code/model directly (so you could edit code, or the model, it was all the one thing). They also had refactoring (which was the first time I remember it post smalltalk environments).
Since that time I haven't seen MDA grow any more in popularity, at least in the mainstream, so in terms of popularity it doesn't appear to be the future (so that kind of answers it).
Of course popularity isn't everything, and things to have a tendency to come back, but for the time being I think MDA+tools is viewed by many as "wizard based code generation" tools (regardless of what it really is) so I think it will be some time or perhaps never that it really takes off.
A: I think, it will take time, till the tools get more refined, more people gain experience with MDD. At the moment if you want to get something out of MDD you have to invest quite a lot, so its use remains limited.
Looking at openArchitectureWare for example: While it is quite robust and basic documentation exists, documentation on the inner workings are missing and there are still problems with scalability, that are undocumented - maybe that will get better when Xtext and Xpand get rewritten.
But despise those limitations the generation itself is quite easy with oAW, you can navigate your models like a charm in Xtend and Xpand and by combining several workflows into bigger workflows, you can also do very complex things. If needed you can resort to Java, so you have a very big flexibility in what you can do with your models. Writing your own DSL with Xtext in oAW, too, is quickly done, yet you get your meta-model, a parser and a very nice editor basically for free. Also you can get your models basically from everywhere, e.g. a component that can convert a database into a meta-model and corresponding models can be written without big effort.
So I would say, MDD is still building up, as tools and experience with it increases. It can already used successfully, if you have the necessary expertise and are ready to push it within your company. In the end, I think, it is a very good thing, because a lot of glue code (aka copy paste) can and should be generated. Doing that with MDD is a very nice and structured way of doing this, that facilitates reusability, in my opinion.
A: One of the problems of MDD is that, since it works on an higher abstraction level, it requires developers that can go up on the abstraction level too. That greatly reduces the universe of developers who can understand and use such methodologies.
A:
Please let me know, if you have any (good or bad) experience with model-driven approaches or why you think it's not interesting at all.
I think the contributors here are part of the "No Silver Bullet" camp (I am definitely). If MDA worked (equals to "huge savings"), we would know it, that is for sure. The question is: how far "meta" can you go while keeping your system manageable? This was the turning point in UML 2.0 when they introduced a more formal meta-meta-model. So far, I haven't seen a real world usage of the modelisation power of UML 2.0 (but my world is rather limited). Besides, you have only two choices with a model-driven approach: generate code, or having a runtime exploiting your model. The ultimate constraint-free code generator is called "human", whereas the ultimate runtimes where found in the 4GLs (what is the current number nowadays?). Maybe that would explain the lack of enthousiasm.
A: We, at itemis (www.itemis.com) use model-driven Software Development alot. So far we had really good experiences. Shure it isn't a silver bullet, but it helps improving software quality hence more use for our customers.
A: Model Driven Development will be the future if and only if the models that it uses can be as flexible as writing the code that it's supposed to be generating. I think the reason why it's not doing so well right now is that you it's difficult to do the same "round-tripping" that text-based programming languages have been doing for decades.
With text-based programming languages, changing the model is as simple as changing a few lines of code. With a graphical programming language (aka an MDD-diagram like UML), you have to find a way to translate that model all the way back down to its text-based equivalent (which was already expressively efficient in the first place) and it can be very, very messy.
IMHO, the only way MDD can ever be useful if it's built from the ground up to be as expressive and as flexible as its text-based counterpart. Attempting to use existing top-down graphical design languages (such as UML) for tools that are inherently built from the bottom-up using layered abstractions (such as programming languages) poses a huge impedance mismatch. I can't quite put my finger on it, but there's still something missing in MDD that would make it as useful as people would claim it to be...
A: This is a very late reply, but I am currently searching for MDD tools to replace Rose RT, which is unfortunately being supplanted by Rhapsody. We are in the real-time, embedded and distributed C++ space and we get a LOT out of MDD. We are trying to move on to a better tool and get more widespread use of the tool in our very large company. It is an uphill battle because of some of the fine reasons mentioned here.
I think of MDD as just one level above the compiler, just as the compiler is above assembly. I want a tool that lets me, as the architect, develop the application framework, and extensively edit the code generation (scripts) to use that framework and whatever middleware we are using for message passing. I want the developers making complete UML classes and state diagrams that include all the code needed to generate the application and/or library.
It is true that you can do anything with code, but I would roughly summarize the benefits of MDD as this:
*
*A few people make the application framework, middleware adapters and glue that to the MDD tool. They build the "house".
*Other people create complete classes, diagrams, and state machine transition code. This lets them focus on the application in stead fo the "house".
*Its easy to see when peopel have wierd design since the diagram is the code. We don't have all expert developers and its nice to bring junior people up this way.
*Mostly its the nasty state machine code that can happen in something like a mobile robotics project. I want people making state diagrams that I can understand, criticize and work on them with.
*You can also have nice refactoring like dragging operation and attributes up inheritence chains or to other classes, etc. I like that better than digging in files.
Even as I type this I realize that you can do everything in code. I like a thin tool jsut on top of the code to enforce uniformity, document the design, and allow a bit easier refactoring.
The main problem I encounter that I don't have a good answer for is that there is no standard set of functionality and file format for such models. People worry about the vendor going away and then being stuck. (We bascially had that happen with Rose RT.) You don't have that with source code. However, you would have the latest version of the tool and the course code that you generated last :). I'm willing to bet that the benefit outweighs the risk.
I have yet to find the tool like this, but I am trying to get a few vendors to listen to me and maybe accept money to make this happen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Simplest way to profile a PHP script What's the easiest way to profile a PHP script?
I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.
I tried experimenting with the microtime function:
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.
A: I would defiantly give BlackFire a try.
There is this virtualBox I've put together using puphpet, to test different php frameworks which coms with BlackFire, please feel free to fork and/or distribute if required :)
https://github.com/webit4me/PHPFrameworks
A: For benchmarking, like in your example, I use the pear Benchmark package. You set markers for measuring. The class also provides a few presentation helpers, or you can process the data as you see fit.
I actually have it wrapped in another class with a __destruct method. When a script exits, the output is logged via log4php to syslog, so I have a lot of performance data to work from.
A: Cross posting my reference from SO Documentation beta which is going offline.
Profiling with XDebug
An extension to PHP called Xdebug is available to assist in profiling PHP applications, as well as runtime debugging. When running the profiler, the output is written to a file in a binary format called "cachegrind". Applications are available on each platform to analyze these files. No application code changes are necessary to perform this profiling.
To enable profiling, install the extension and adjust php.ini settings. Some Linux distributions come with standard packages (e.g. Ubuntu's php-xdebug package). In our example we will run the profile optionally based on a request parameter. This allows us to keep settings static and turn on the profiler only as needed.
# php.ini settings
# Set to 1 to turn it on for every request
xdebug.profiler_enable = 0
# Let's use a GET/POST parameter to turn on the profiler
xdebug.profiler_enable_trigger = 1
# The GET/POST value we will pass; empty for any value
xdebug.profiler_enable_trigger_value = ""
# Output cachegrind files to /tmp so our system cleans them up later
xdebug.profiler_output_dir = "/tmp"
xdebug.profiler_output_name = "cachegrind.out.%p"
Next use a web client to make a request to your application's URL you wish to profile, e.g.
http://example.com/article/1?XDEBUG_PROFILE=1
As the page processes it will write to a file with a name similar to
/tmp/cachegrind.out.12345
By default the number in the filename is the process id which wrote it. This is configurable with the xdebug.profiler_output_name setting.
Note that it will write one file for each PHP request / process that is executed. So, for example, if you wish to analyze a form post, one profile will be written for the GET request to display the HTML form. The XDEBUG_PROFILE parameter will need to be passed into the subsequent POST request to analyze the second request which processes the form. Therefore when profiling it is sometimes easier to run curl to POST a form directly.
Analyzing the Output
Once written the profile cache can be read by an application such as KCachegrind or Webgrind. PHPStorm, a popular PHP IDE, can also display this profiling data.
KCachegrind, for example, will display information including:
*
*Functions executed
*Call time, both itself and inclusive of subsequent function calls
*Number of times each function is called
*Call graphs
*Links to source code
What to Look For
Obviously performance tuning is very specific to each application's use cases. In general it's good to look for:
*
*Repeated calls to the same function you wouldn't expect to see. For functions that process and query data these could be prime opportunities for your application to cache.
*Slow-running functions. Where is the application spending most of its time? the best payoff in performance tuning is focusing on those parts of the application which consume the most time.
Note: Xdebug, and in particular its profiling features, are very resource intensive and slow down PHP execution. It is recommended to not run these in a production server environment.
A: You want xdebug I think. Install it on the server, turn it on, pump the output through kcachegrind (for linux) or wincachegrind (for windows) and it'll show you a few pretty charts that detail the exact timings, counts and memory usage (but you'll need another extension for that).
It rocks, seriously :D
A: If subtracting microtimes gives you negative results, try using the function with the argument true (microtime(true)). With true, the function returns a float instead of a string (as it does if it is called without arguments).
A: Honestly, I am going to argue that using NewRelic for profiling is the best.
It's a PHP extension which doesn't seem to slow down runtime at all and they do the monitoring for you, allowing decent drill down. In the expensive version they allow heavy drill down (but we can't afford their pricing model).
Still, even with the free/standard plan, it's obvious and simple where most of the low hanging fruit is. I also like that it can give you an idea on DB interactions too.
A: Poor man's profiling, no extensions required. Supports nested profiles and percent of total:
function p_open($flag) {
global $p_times;
if (null === $p_times)
$p_times = [];
if (! array_key_exists($flag, $p_times))
$p_times[$flag] = [ 'total' => 0, 'open' => 0 ];
$p_times[$flag]['open'] = microtime(true);
}
function p_close($flag)
{
global $p_times;
if (isset($p_times[$flag]['open'])) {
$p_times[$flag]['total'] += (microtime(true) - $p_times[$flag]['open']);
unset($p_times[$flag]['open']);
}
}
function p_dump()
{
global $p_times;
$dump = [];
$sum = 0;
foreach ($p_times as $flag => $info) {
$dump[$flag]['elapsed'] = $info['total'];
$sum += $info['total'];
}
foreach ($dump as $flag => $info) {
$dump[$flag]['percent'] = $dump[$flag]['elapsed']/$sum;
}
return $dump;
}
Example:
<?php
p_open('foo');
sleep(1);
p_open('bar');
sleep(2);
p_open('baz');
sleep(3);
p_close('baz');
sleep(2);
p_close('bar');
sleep(1);
p_close('foo');
var_dump(p_dump());
Yields:
array:3 [
"foo" => array:2 [
"elapsed" => 9.000766992569
"percent" => 0.4736904954747
]
"bar" => array:2 [
"elapsed" => 7.0004580020905
"percent" => 0.36841864946596
]
"baz" => array:2 [
"elapsed" => 3.0001420974731
"percent" => 0.15789085505934
]
]
A: XDebug is not stable and it's not always available for particular php version. For example on some servers I still run php-5.1.6, -- it's what comes with RedHat RHEL5 (and btw still receives updates for all important issues), and recent XDebug does not even compile with this php. So I ended up with switching to DBG debugger
Its php benchmarking provides timing for functions, methods, modules and even lines.
A: You all should definitely check this new php profiler.
https://github.com/NoiseByNorthwest/php-spx
It redefines the way of how php profilers collects and presents the result.
Instead of outputting just a total number of particular function calls and total time spent of executing it - PHP-SPX presents the whole timeline of request execution in a perfectly readable way. Below is the screen of GUI it provides.
A: PECL XHPROF looks interensting too. It has clickable HTML interface for viewing reports and pretty straightforward documentation. I have yet to test it though.
A: No extensions are needed, just use these two functions for simple profiling.
// Call this at each point of interest, passing a descriptive string
function prof_flag($str)
{
global $prof_timing, $prof_names;
$prof_timing[] = microtime(true);
$prof_names[] = $str;
}
// Call this when you're done and want to see the results
function prof_print()
{
global $prof_timing, $prof_names;
$size = count($prof_timing);
for($i=0;$i<$size - 1; $i++)
{
echo "<b>{$prof_names[$i]}</b><br>";
echo sprintf(" %f<br>", $prof_timing[$i+1]-$prof_timing[$i]);
}
echo "<b>{$prof_names[$size-1]}</b><br>";
}
Here is an example, calling prof_flag() with a description at each checkpoint, and prof_print() at the end:
prof_flag("Start");
include '../lib/database.php';
include '../lib/helper_func.php';
prof_flag("Connect to DB");
connect_to_db();
prof_flag("Perform query");
// Get all the data
$select_query = "SELECT * FROM data_table";
$result = mysql_query($select_query);
prof_flag("Retrieve data");
$rows = array();
$found_data=false;
while($r = mysql_fetch_assoc($result))
{
$found_data=true;
$rows[] = $r;
}
prof_flag("Close DB");
mysql_close(); //close database connection
prof_flag("Done");
prof_print();
Output looks like this:
Start 0.004303Connect to DB 0.003518Perform query 0.000308Retrieve data 0.000009Close DB 0.000049Done
A: The PECL APD extension is used as follows:
<?php
apd_set_pprof_trace();
//rest of the script
?>
After, parse the generated file using pprofp.
Example output:
Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time = 0.00
Total User Time = 0.00
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main
56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace
28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace
14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace
Warning: the latest release of APD is dated 2004, the extension is no longer maintained and has various compability issues (see comments).
A: I like to use phpDebug for profiling.
http://phpdebug.sourceforge.net/www/index.html
It outputs all time / memory usage for any SQL used as well as all the included files. Obviously, it works best on code that's abstracted.
For function and class profiling I'll just use microtime() + get_memory_usage() + get_peak_memory_usage().
A: In case you're a fan of VS Code, there is a quick and simple (free) extension PHP Profiler.
This gives you simple function call times and hotpaths
highlighting right in your code.
More details: https://docs.devsense.com/vscode/profiling
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "319"
} |
Q: Adding NUnit to the options for ASP.NET MVC test framework
*
*I have nUnit installed.
*I have VS2008 Team Edition installed.
*I have ASP.Net MVC Preview 4 (Codeplex) installed.
How do I make Visual Studio show me nUnit as a testing framework when creating a new MVC project? At this point I still only have the Microsoft Testing Framework as a choice.
Update: I installed nUnit 2.5, but still with no success. From what I've found Googling, it would seem I need to create templates for the test projects in order for them to be displayed in the "Create Unit Test Project". I would have thought that templates be readily available for nUnit, xUnit, MBUnit, et. al. Also, it looks like I need to created registry entries. Anybody have any additional information?
Update: I determined the answer to this through research and it's posted below.
A: After a bunch of research and experimentation, I've found the answer.
*
*For the record, the current release of nUnit 2.5 Alpha does not seem to contain templates for test projects in Visual Studio 2008.
*I followed the directions here which describe how to create your own project templates and then add appropriate registry entries that allow your templates to appear in the drop-down box in the Create Unit Test Project dialog box of an MVC project.
From a high level, what you have to do is:
*
*Create a project
*Export it as a template (which results in a single ZIP archive)
*Copy it from the local user's template folder to the Visual Studio main template test folder
*Execute devenv.exe /setup
*Run regedit and create a few registry entries.
So much for the testing framework selection being easy! Although, to be fair MVC is not even beta yet.
After all that, I did get the framework of choice (NUnit) to show up in the drop down box. However, there was still a bit left to be desired:
*
*Although the test project gets properly created, it did not automatically have a project reference to the main MVC project. When using Visual Studio Unit Test as the test project, it automatically does this.
*I tried to open the ZIP file produced and edit the MyTemplate.vssettings file as well as the .csproj project file in order to correct the aforementioned issue as well as tweak the names of things so they'd appear more user friendly. This for some reason does not work. The ZIP file produced can not be updated via WinZip or Win-Rar -- each indicates the archive is corrupt. Each can extract the contents, though. So, I tried updating the extracted files and then recreating the ZIP file. Visual Studio did not like it.
So, I should probably read this as well which discusses making project templates for Visual Studio (also referenced in the blog post I linked to above.) I admit to being disappointed though; from all the talk about MVC playing well with other testing frameworks, etc, I thought that it'd be easier to register a 3rd party framework.
A: Man, they have VS 2008 project template listed in their release notes. I guess that doesn't mean they have it integrated with the dialog yet.
I use MbUnit with Gallio and everything worked like a charm. I had to install an Alpha of Gallio and MbUnit and when I read the above in the release notes, I figured they implemented it also.
Just keep a look out on nUnit's site for future alpha releases. I am sure they'll have it implemented soon. You could also implement the feature yourself and submit a patch. :-)
A: Although they do not have one bundled with the framework here is a link to post containing a download to automatically create the test project for "NUnit with moq" for you NUnit with Moq
(did not work right away on my computer, W7 Beta, make sure you use elevated permissions)
A: Do install Testdriven.net to integrate NUnit with Visual Studio. MbUnit and later versions of NUnit also contain project templates for unit tests.
You can use those project templates to create a test project and then reference to your ASP.NET MVC project and be able to test its code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: How do I use Linq for paging a generic collection? I've got a System.Generic.Collections.List(Of MyCustomClass) type object.
Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?
A: Hi There is a wicked thing called PagedList which i got when watching a Rob Conery Screen Cast.
http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/
It has all the Skip and Take stuff built in.
All you do is call
var query = from item in DB.Table
where item.Field == 1
orderby item.Field2
select item;
PagedList<MyType> pagedList = query.ToPagedList(pageIndex, pageSize);
Hope it helps.. I'm using it now and it works ok for linq to entities. With Linq to entities you have to perform an Orderby before you can use Skip and Take.
A: If you have your linq-query that contains all the rows you want to display, this code can be used:
var pageNum = 3;
var pageSize = 20;
query = query.Skip((pageNum - 1) * pageSize).Take(pageSize);
You can also make an extension method on the object to be able to write
query.Page(2,50)
to get the first 50 records of page 2. If that is want you want, the information is on the solid code blog.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: db4o experiences? I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o?
A: We run DB40 .NET version in a large client/server project.
Our experiences is that you can potentially get much better performance than typical relational databases.
However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship.
Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects.
Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want.
Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these "reflection" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index("someField"), which is not strongly typed.
We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database.
We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database.
We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing:
// C# syntax for "Find all MyFoos with Bar == 23".
// (Note the Java syntax is more verbose using the Predicate class.)
IList<MyFoo> results = db4o.Query<MyFoo>(input => input.Bar == 23);
Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed.
For .NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries.
DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.)
If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it.
update July 2015 Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written.
A: Most native queries can and are efficiently converted into SODA queries behind the scenes so that should not make a difference. Using NQ is of course preferred as you remain in the realms of strong typed language. If you have problems getting NQ to use indexes please feel free to post your problem to the db4o forums and we'll try to help you out.
Goran
A: Main problem I've encountered with it is reporting. There just doesn't seem to be any way to run efficient reports against a db4o data source.
A: Judah, it sounds like you are not using transparent activation, which is a feature of the latest production version (7.4)? Perhaps if you specified the version you are using as there may be other issues which are now resolved in the latest version?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Get application name from Windows XP cut and paste? This is a bit of a long shot, but if anyone can figure it out, you guys can...
In Windows XP, is there any meta-data that comes with a cut and paste action, from which I can ascertain the application that provided the clipboard contents?
Bonus question... if there is such information, is there any way I can access it through a Java app?
A: The API function GetClipboardOwner returns the clipboard owner
(http://msdn.microsoft.com/en-us/library/ms649041(VS.85).aspx), -sorry cannot mark as link because the "()" in the URL-
Don't know Java, I suppose you can call native API functions from inside the Java VM.
A "quick and dirty" approach could be using an AutoHotKey script to intercept the CTRL+C / CTRL+INS hotkeys, grab the id of the active process (in a file or any place that can be accessed by the Java app) and proceed with the clipboard copy. The AutoHotKey part shouldn't be difficult, don't know about the Java part.
A: That depends on the clipboard format. If it is plain-text, then no. Unless you want to install global hooks on the clipboard.
Which you cannot do from Java.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Visual Web Developer (Express): Setting Document Root for Dev Environment I'm developing a site in Visual Web Dev Express, and when I run/debug, I'd like to be able to set my application's document root so that I can use safer paths, like "/css/style.css' instead of "css/style.css". How would I accomplish this?
A: *
*Click on the web site node in the solution explorer.
*Press F4 to see the properties window.
*Change the virtual path from /projectname to /
Bear in mind that this has an impact on how you expect the application/web site to be deployed. If it is ever used outside the root of a web server, the URL paths will be incorrect.
A: I have been looking for the virtual path field in the properties window but haven't been able to find it... it only shows me the following options
*
*aperture directory URL
*complete access route
*policy file
*port
*use dynamic port
Do you know of some place else where I could find the Virtual Path field?
A: Select the "Web" tab and it's in the Servers section
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Page a Generic Collection Without Linq I've got a System.Generic.Collections.List(Of MyCustomClass) type object.
Given integer varaibles pagesize and pagenumber, how can I collect only any single page of MyCustomClass objects?
This is what I've got. How can I improve it?
'my given collection and paging parameters
Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN
Dim pagesize As Integer = GIVEN
Dim pagenumber As Integer = GIVEN
'collect current page objects
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
Dim objcount As Integer = 1
For Each obj As MyCustomClass In AllOfMyCustomClassObjects
If objcount > pagesize * (pagenumber - 1) And count <= pagesize * pagenumber Then
PageObjects.Add(obj)
End If
objcount = objcount + 1
Next
'find total page count
Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize))
If objcount Mod pagesize > 0 Then
totalpages = totalpages + 1
End If
A: Generic.List should provide the Skip() and Take() methods, so you could do this:
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
PageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize)
If by "without Linq" you meant on the 2.0 Framework, I don't believe List(Of T) supports those methods. In that case, use GetRange like Jonathan suggested.
A: You use GetRange on your IEnuramble implementing collection:
List<int> lolInts = new List<int>();
for (int i = 0; i <= 100; i++)
{
lolInts.Add(i);
}
List<int> page1 = lolInts.GetRange(0, 49);
List<int> page2 = lilInts.GetRange(50, 100);
I trust you can figure out how to use GetRange to grab an individual page from here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Anyone have a link to a technical discussion of anything akin to the Facebook news feed system? I'm looking for a presentation, PDF, blog post, or whitepaper discussing the technical details of how to filter down and display massive amounts of information for individual users in an intelligent (possibly machine learning) kind of way. I've had coworkers hear presentations on the Facebook news feed but I can't find anything published anywhere that goes into the dirty details. Searches seem to just turn up the controversy of the system. Maybe I'm not searching for the right keywords...
@AlexCuse I'm trying to build something similar to Facebook's system. I have large amounts of data and I need to filter it down to something manageable to present to the user. I cannot use another website due to the scale of what I've got to work at. Also I just want a technical discussion of how to implement it, not examples of people who have an implementation.
A: Are you looking for something along the lines of distributed pub/sub with content based filtering? If so, you may want to look into Siena and some of the associated papers such as Design and Evaluation of a Wide-Area Event Notification Service
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create a mapping table in SQL Server Management Studio? I'm learning about table design in SQL and I'm wonder how to create a mapping table in order to establish a many-to-many relationship between two other tables?
I think the mapping table needs two primary keys - but I can't see how to create that as it appears there can only be 1 primary key column?
I'm using the Database Diagrams feature to create my tables and relationships.
A: The easiest way is to simply select both fields by selecting the first field, and then while holding down the Ctrl key selecting the second field. Then clicking the key icon to set them both as the primary key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Comparing IEEE floats and doubles for equality What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.
A: The best approach I think is to compare ULPs.
bool is_nan(float f)
{
return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<unsigned __int32*>(&f) & 0x007fffff) != 0;
}
bool is_finite(float f)
{
return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) != 0x7f800000;
}
// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)
// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other
#define UNEQUAL_NANS 1
// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)
// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX
#define INFINITE_INFINITIES 1
// test whether two IEEE floats are within a specified number of representable values of each other
// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers
bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)
{
#ifdef UNEQUAL_NANS
if(is_nan(lhs) || is_nan(rhs))
{
return false;
}
#endif
#ifdef INFINITE_INFINITIES
if((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs)))
{
return false;
}
#endif
signed __int32 left(*reinterpret_cast<signed __int32*>(&lhs));
// transform signed magnitude ints into 2s complement signed ints
if(left < 0)
{
left = 0x80000000 - left;
}
signed __int32 right(*reinterpret_cast<signed __int32*>(&rhs));
// transform signed magnitude ints into 2s complement signed ints
if(right < 0)
{
right = 0x80000000 - right;
}
if(static_cast<unsigned __int32>(std::abs(left - right)) <= max_ulp_difference)
{
return true;
}
return false;
}
A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are.
I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then.
A: The current version I am using is this
bool is_equals(float A, float B,
float maxRelativeError, float maxAbsoluteError)
{
if (fabs(A - B) < maxAbsoluteError)
return true;
float relativeError;
if (fabs(B) > fabs(A))
relativeError = fabs((A - B) / B);
else
relativeError = fabs((A - B) / A);
if (relativeError <= maxRelativeError)
return true;
return false;
}
This seems to take care of most problems by combining relative and absolute error tolerance. Is the ULP approach better? If so, why?
A:
@DrPizza: I am no performance guru but I would expect fixed point operations to be quicker than floating point operations (in most cases).
It rather depends on what you are doing with them. A fixed-point type with the same range as an IEEE float would be many many times slower (and many times larger).
Things suitable for floats:
3D graphics, physics/engineering, simulation, climate simulation....
A: In numerical software you often want to test whether two floating point numbers are exactly equal. LAPACK is full of examples for such cases. Sure, the most common case is where you want to test whether a floating point number equals "Zero", "One", "Two", "Half". If anyone is interested I can pick some algorithms and go more into detail.
Also in BLAS you often want to check whether a floating point number is exactly Zero or One. For example, the routine dgemv can compute operations of the form
*
*y = beta*y + alpha*A*x
*y = beta*y + alpha*A^T*x
*y = beta*y + alpha*A^H*x
So if beta equals One you have an "plus assignment" and for beta equals Zero a "simple assignment". So you certainly can cut the computational cost if you give these (common) cases a special treatment.
Sure, you could design the BLAS routines in such a way that you can avoid exact comparisons (e.g. using some flags). However, the LAPACK is full of examples where it is not possible.
P.S.:
*
*There are certainly many cases where you don't want check for "is exactly equal". For many people this even might be the only case they ever have to deal with. All I want to point out is that there are other cases too.
*Although LAPACK is written in Fortran the logic is the same if you are using other programming languages for numerical software.
A: Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.
A:
Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.
Even if it causes it to copy from vector registers to integer registers via memory, and even if it stalls the pipeline, it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.
i.e. it is a price worth paying.
A:
it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.
If you have floating point errors you have even more problems than this. Although I guess that is up to personal perspective.
A:
This seems to take care of most problems by combining relative and absolute error tolerance. Is the ULP approach better? If so, why?
ULPs are a direct measure of the "distance" between two floating point numbers. This means that they don't require you to conjure up the relative and absolute error values, nor do you have to make sure to get those values "about right". With ULPs, you can express directly how close you want the numbers to be, and the same threshold works just as well for small values as for large ones.
A:
If you have floating point errors you have even more problems than this. Although I guess that is up to personal perspective.
Even if we do the numeric analysis to minimize accumulation of error, we can't eliminate it and we can be left with results that ought to be identical (if we were calculating with reals) but differ (because we cannot calculate with reals).
A: If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.
A:
If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.
Perhaps we cannot afford the loss of range or performance that such an approach would inflict.
A:
If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.
Perhaps I should explain the problem better. In C++, the following code:
#include <iostream>
using namespace std;
int main()
{
float a = 1.0;
float b = 0.0;
for(int i=0;i<10;++i)
{
b+=0.1;
}
if(a != b)
{
cout << "Something is wrong" << endl;
}
return 1;
}
prints the phrase "Something is wrong". Are you saying that it should?
A: @DrPizza: I am no performance guru but I would expect fixed point operations to be quicker than floating point operations (in most cases).
@Craig H: Sure. I'm totally okay with it printing that. If a or b store money then they should be represented in fixed point. I'm struggling to think of a real world example where such logic ought to be allied to floats. Things suitable for floats:
*
*weights
*ranks
*distances
*real world values (like from a ADC)
For all these things, either you much then numbers and simply present the results to the user for human interpretation, or you make a comparative statement (even if such a statement is, "this thing is within 0.001 of this other thing"). A comparative statement like mine is only useful in the context of the algorithm: the "within 0.001" part depends on what physical question you're asking. That my 0.02. Or should I say 2/100ths?
A:
It rather depends on what you are
doing with them. A fixed-point type
with the same range as an IEEE float
would be many many times slower (and
many times larger).
Okay, but if I want a infinitesimally small bit-resolution then it's back to my original point: == and != have no meaning in the context of such a problem.
An int lets me express ~10^9 values (regardless of the range) which seems like enough for any situation where I would care about two of them being equal. And if that's not enough, use a 64-bit OS and you've got about 10^19 distinct values.
I can express values a range of 0 to 10^200 (for example) in an int, it is just the bit-resolution that suffers (resolution would be greater than 1, but, again, no application has that sort of range as well as that sort of resolution).
To summarize, I think in all cases one either is representing a continuum of values, in which case != and == are irrelevant, or one is representing a fixed set of values, which can be mapped to an int (or a another fixed-precision type).
A:
An int lets me express ~10^9 values
(regardless of the range) which seems
like enough for any situation where I
would care about two of them being
equal. And if that's not enough, use a
64-bit OS and you've got about 10^19
distinct values.
I have actually hit that limit... I was trying to juggle times in ps and time in clock cycles in a simulation where you easily hit 10^10 cycles. No matter what I did I very quickly overflowed the puny range of 64-bit integers... 10^19 is not as much as you think it is, gimme 128 bits computing now!
Floats allowed me to get a solution to the mathematical issues, as the values overflowed with lots zeros at the low end. So you basically had a decimal point floating aronud in the number with no loss of precision (I could like with the more limited distinct number of values allowed in the mantissa of a float compared to a 64-bit int, but desperately needed th range!).
And then things converted back to integers to compare etc.
Annoying, and in the end I scrapped the entire attempt and just relied on floats and < and > to get the work done. Not perfect, but works for the use case envisioned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What is the easiest-to-use web "rich text editor" I am looking for a text editor to be used in a web page. Where users can format the text and get a WYSIWYG experience. Doesn't need to be too fancy. But has to be easy to use and integrate into the page. Has to generate HTML as output. Support AJAX (one I checked works only with standard form submit) and has to be small in terms of download to the user's browser.
A: TinyMCE is the simplest I've found to use. I've never used it in an AJAX-enabled application, but there are instructions on how to do so on the project's wiki.
A: Try FCKeditor. It supports integration with most popular platforms, and it's fairly lightweight.
A: You might also want to look at YUI's Rich Text Editor.
If you're starting your site from scratch or haven't invested a lot of effort into another JavaScript platform, Yahoo User Interface (YUI) is a very complete JavaScript library that could help you add other AJAX elements beyond a text editor.
A: I just did a full day of evaluation of all the ones mentioned so far (and then some), and the one I liked the best is Obout Editor. I think it might be for ASP.NET only, so it might not work for you, but if you are using .NET, it's great. The HTML output is clean and nicely styled, and the rendered output looks the same in the editor as it does when you output it to the page (something I had trouble with when using the others due to doctype settings in the editor). It costs a few bucks, but it was worth it for us.
A: I found TinyMCE pretty easy to implement. And it's light on bandwidth usage too.
A: Well it depends what platform you are on if you are looking for server-side functionality as well, but the defacto badass WYSIWYg in my opinion is FCKeditor. I have worked with this personally in numerous environments (both professional and hobby level) and have always been impressed.
It's certainly worth a look. I believe it is employed by open source projects such as SubText as well. Perhaps, Jon Galloway can add to this if he reads this question. Or Phil if he is currently a user.
A: Using fck for some tine now, after "free text box", or something like that. Had problems only once, when I put fck inside asp.net ajax updatepanel, but found fix on forums. Problem was solved in next release.
I would like to see some nice photo browser in it, because fck comes only with simple browser that displays filename, no thumbs. The other one, that has thumbs costs bunch of money.
Didn't try it with asp.net mvc, don't know how will uploading work. It uses one ascx for wrapping js functionality.
A: i started out using free text box when i was doing a lot of asp.net programming, but now that most of what i do is php i've moved to the FCK editor.
while the change wasn't necessarily prompted by the language, i feel that the fck editor is a better choice because of it's versatility.
A: For something minimalist, take a look at Widg Editor, it's truly tiny and very simple. It's only haphazardly supported as a hobby project though.
I'm currently using the RTE component of DynarchLib, which is highly customisable - definitely does AJAX - but a bit complicated and not very pretty. It is actively supported, and you can get answers on their forum very quickly.
I previously tried Dojo's editor, and found it broken and badly undocumented. YMMV.
Edit: In response to other people's answers, I've now tried TinyMCE and found it to be excellent. More easily configurable and far fewer problems than anything else I've tried. Use TinyMCE!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Am I missing something about LINQ? I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.
I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?
A: So the really, really big deal about LINQ has nothing to do with Linq to SQL. It's about the enhancements it brought to the C# language itself.
A: LINQ is not just an ORM system, as Jonathan pointed out it brings a lot of functional programming elements to C#. And it lets you do a lot of "database-y" things in regular C# code. It's difficult to explain just how incredibly powerful that can be. Consider how much having solid, well designed generic data structures (such as list, stack, dictionary/hash, etc.) included in common frameworks has improved the state of development in modern languages. Precisely because using these data structures is very common and reducing the intellectual overhead of using them is a huge benefit. LINQ doesn't do anything you can't do yourself, but it makes a lot of operations a lot more straightforward and a lot easier.
Consider the time-honored example of removing duplicates from a non-ordered list. In a lower level language like C or C++ you'd probably have to sort the list and maintain two indices into the list as you removed dupes. In a language with hashes (Java, C#, Javascript, Perl, etc.) you could create a hash where the keys are the unique values, then extract the keys into a new list. With LINQ you could just do this:
int[] data = { 0, 1, 3, 3, 7, 8, 0, 9, 2, 1 };
var uniqueData = data.GroupBy(i => i).Select(g => g.Key);
A: LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects.
LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time.
Take the task of finding the intersection of two lists:
Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code.
foreach (int number in list1)
{
foreach (int number2 in list2)
{
if (number2 == number)
{
returnList.add(number2);
}
}
}
Using LINQ, it does the same thing in one line of code:
var results = list1.Intersect(list2);
You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.
A: Because linq is really monads in sql clothing, I'm using it on a project to make asynchronous web requests with the continuation monad, and it's proving to work really well!
Check out these articles:
http://www.aboutcode.net/2008/01/14/Async+WebRequest+Using+LINQ+Syntax.aspx
http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx
From the first article:
var requests = new[]
{
WebRequest.Create("http://www.google.com/"),
WebRequest.Create("http://www.yahoo.com/"),
WebRequest.Create("http://channel9.msdn.com/")
};
var pages = from request in requests
select
from response in request.GetResponseAsync()
let stream = response.GetResponseStream()
from html in stream.ReadToEndAsync()
select new { html, response };
foreach (var page in pages)
{
page(d =>
{
Console.WriteLine(d.response.ResponseUri.ToString());
Console.WriteLine(d.html.Substring(0, 40));
Console.WriteLine();
});
}
A: Before:
// Init Movie
m_ImageArray = new Image[K_NB_IMAGE];
Stream l_ImageStream = null;
Bitmap l_Bitmap = null;
// get a reference to the current assembly
Assembly l_Assembly = Assembly.GetExecutingAssembly();
// get a list of resource names from the manifest
string[] l_ResourceName = l_Assembly.GetManifestResourceNames();
foreach (string l_Str in l_ResourceName)
{
if (l_Str.EndsWith(".png"))
{
// attach to stream to the resource in the manifest
l_ImageStream = l_Assembly.GetManifestResourceStream(l_Str);
if (!(null == l_ImageStream))
{
// create a new bitmap from this stream and
// add it to the arraylist
l_Bitmap = Bitmap.FromStream(l_ImageStream) as Bitmap;
if (!(null == l_Bitmap))
{
int l_Index = Convert.ToInt32(l_Str.Substring(l_Str.Length - 6, 2));
l_Index -= 1;
if (l_Index < 0) l_Index = 0;
if (l_Index > K_NB_IMAGE) l_Index = K_NB_IMAGE;
m_ImageArray[l_Index] = l_Bitmap;
}
l_Bitmap = null;
l_ImageStream.Close();
l_ImageStream = null;
} // if
} // if
} // foreach
After:
Assembly l_Assembly = Assembly.GetExecutingAssembly();
//Linq is the tops
m_ImageList = l_Assembly.GetManifestResourceNames()
.Where(a => a.EndsWith(".png"))
.OrderBy(b => b)
.Select(c => l_Assembly.GetManifestResourceStream(c))
.Where(d => d != null) //ImageStream not null
.Select(e => Bitmap.FromStream(e))
.Where(f => f != null) //Bitmap not null
.ToList();
Or, alternatively (query syntax):
Assembly l_Assembly = Assembly.GetExecutingAssembly();
//Linq is the tops
m_ImageList = (
from resource in l_Assembly.GetManifestResourceNames()
where resource.EndsWith(".png")
orderby resource
let imageStream = l_Assembly.GetManifestResourceStream(resource)
where imageStream != null
let bitmap = Bitmap.FromStream(imageStream)
where bitmap != null)
.ToList();
A: The point is that LINQ integrates your queries into your primary programming language, allowing your IDE to provide you with some facilities (Intellisense and debug support, for example) that you otherwise would not have, and to allow the compiler to type-check your SQL code (which is impossible with a normal string query).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Which .NET Dependency Injection frameworks are worth looking into? Which C#/.NET Dependency Injection frameworks are worth looking into?
And what can you say about their complexity and speed.
A: I'm a huge fan of Castle. I love the facilities it also provides beyond the IoC Container story. It really simplfies using NHibernate, logging, AOP, etc. I also use Binsor for configuration with Boo and have really fallen in love with Boo as a language because of it.
A: It depends on what you are looking for, as they each have their pros and cons.
*
*Spring.NET is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
*Castle Windsor is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
*Structure Map has very rich and fine grained configuration through an internal DSL.
*Autofac is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
*Ninject I have heard is more bare bones with a less is more approach (heard not experienced).
*The biggest discriminator of Unity is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.
So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.
A: I spent the better part of a day struggling without success to get the simplest Spring.NET example working. Could never figure out how to get it to find my assembly from the XML file. In about 2 hours, on the other hand, I was able to get Ninject working, including testing integration with both NUnit and MSTest.
A: I've used Spring.NET in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the documentation to get it set up.
A: I can recommend Ninject. It's incredibly fast and easy to use but only if you don't need XML configuration, else you should use Windsor.
A: Autofac. https://github.com/autofac/Autofac It is really fast and pretty good. Here is a link with comparisons (made after Ninject fixed a memory leak issue).
http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html
A: edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc:
*
*Castle Windsor - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Silverlight
*Unity - Lightweight extensible dependency injection container with support for constructor, property, and method call injection
*Autofac - An addictive .NET IoC container
*DryIoc - Simple, fast all fully featured IoC container.
*Ninject - The ninja of .NET dependency injectors
*Spring.Net - Spring.NET is an open source application framework that makes building enterprise .NET applications easier
*Lamar - A fast IoC container heavily optimized for usage within ASP.NET Core and other .NET server side applications.
*LightInject - A ultra lightweight IoC container
*Simple Injector - Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.
*Microsoft.Extensions.DependencyInjection - The default IoC container for ASP.NET Core applications.
*Scrutor - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection.
*VS MEF - Managed Extensibility Framework (MEF) implementation used by Visual Studio.
*TinyIoC - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike.
*Stashbox - A lightweight, fast and portable dependency injection framework for .NET based solutions.
Original answer follows.
I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.
That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.
Update
I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.
Other IoC screencasts can also be found here on Dimecasts.
A: The great thing about C# is that it is following a path beaten by years of Java developers before it. So, my advice, generally speaking when looking for tools of this nature, is to look for the solid Java answer and see if there exists a .NET adaptation yet.
So when it comes to DI (and there are so many options out there, this really is a matter of taste) is Spring.NET. Additionally, it's always wise to research the people behind projects. I have no issue suggesting SourceGear products for source control (outside of using them) because I have respect for Eric Sink. I have seen Mark Pollack speak and what can I say, the guy just gets it.
In the end, there are a lot of DI frameworks and your best bet is to do some sample projects with a few of them and make an educated choice.
Good luck!
A: I think a good place to start is with Ninject, it is new and has taken into account alot of fine tuning and is really fast. Nate, the developer, really has a great site and great support.
A: Spring.Net is quite solid, but the documentation took some time to wade through. Autofac is good, and while .Net 2.0 is supported, you need VS 2008 to compile it, or else use the command line to build your app.
A: Ninject is great. It seems really fast, but I haven't done any comparisons. I know Nate, the author, did some comparisons between Ninject and other DI frameworks and is looking for more ways to improve the speed of Ninject.
I've heard lots of people I respect say good things about StructureMap and CastleWindsor. Those, in my mind, are the big three to look at right now.
A: I use Simple Injector:
Simple Injector is an easy, flexible and fast dependency injection library that uses best practice to guide your solutions toward the pit of success.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "401"
} |
Q: Dynamically load a JavaScript file How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.
The client that uses the component isn't required to load all the library script files (and manually insert <script> tags into their web page) that implement this component - just the 'main' component script file.
How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)? Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?
An addition to this question: is there a way to handle the event after a dynamically included JavaScript file is loaded? Prototype has document.observe for document-wide events. Example:
document.observe("dom:loaded", function() {
// initially hide all containers for tab content
$$('div.tabcontent').invoke('hide');
});
What are the available events for a script element?
A: You may create a script element dynamically, using Prototypes:
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
The problem here is that we do not know when the external script file is fully loaded.
We often want our dependant code on the very next line and like to write something like:
if (iNeedSomeMore) {
Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
myFancyMethod(); // cool, no need for callbacks!
}
There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.
If you use Prototype the Script.load method looks like this:
var Script = {
_loadedScripts: [],
include: function(script) {
// include script only once
if (this._loadedScripts.include(script)) {
return false;
}
// request file synchronous
var code = new Ajax.Request(script, {
asynchronous: false,
method: "GET",
evalJS: false,
evalJSON: false
}).transport.responseText;
// eval code on global level
if (Prototype.Browser.IE) {
window.execScript(code);
} else if (Prototype.Browser.WebKit) {
$$("head").first().insert(Object.extend(
new Element("script", {
type: "text/javascript"
}), {
text: code
}
));
} else {
window.eval(code);
}
// remember included script
this._loadedScripts.push(script);
}
};
A: There is no import / include / require in javascript, but there are two main ways to achieve what you want:
1 - You can load it with an AJAX call then use eval.
This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.
2 - Add a script element with the script URL in the HTML.
Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the script element in the head element of the web page, or at the bottom of the body.
Both of these solutions are discussed and illustrated here.
Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.
It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.
E.G : my_lovely_script.js contains MySuperObject
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
var s = new MySuperObject();
Error : MySuperObject is undefined
Then you reload the page hitting F5. And it works! Confusing...
So what to do about it ?
Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :
function loadScript(url, callback)
{
// adding the script element to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// then bind the event to the callback function
// there are several events for cross browser compatibility
script.onreadystatechange = callback;
script.onload = callback;
// fire the loading
head.appendChild(script);
}
Then you write the code you want to use AFTER the script is loaded in a lambda function :
var myPrettyCode = function() {
// here, do what ever you want
};
Then you run all that :
loadScript("my_lovely_script.js", myPrettyCode);
Ok, I got it. But it's a pain to write all this stuff.
Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :
$.getScript("my_lovely_script.js", function() {
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
A: If you have jQuery loaded already, you should use $.getScript.
This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching.
A: If you want a SYNC script loading, you need to add script text directly to HTML HEAD element. Adding it as will trigger an ASYNC load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):
/*sample requires an additional method for array prototype:*/
if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) { if (this[i] === obj) return true; }
return false;
};
};
/*define object that will wrap our logic*/
var ScriptLoader = {
LoadedFiles: [],
LoadFile: function (url) {
var self = this;
if (this.LoadedFiles.contains(url)) return;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
self.LoadedFiles.push(url);
self.AddScript(xhr.responseText);
} else {
if (console) console.error(xhr.statusText);
}
}
};
xhr.open("GET", url, false);/*last parameter defines if call is async or not*/
xhr.send(null);
},
AddScript: function (code) {
var oNew = document.createElement("script");
oNew.type = "text/javascript";
oNew.textContent = code;
document.getElementsByTagName("head")[0].appendChild(oNew);
}
};
/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/
ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id "tb1"*/
$(function () { alert($('#tb1').val()); });
A: With Promises you can simplify it like this.
Loader function:
const loadCDN = src =>
new Promise((resolve, reject) => {
if (document.querySelector(`head > script[src="${src}"]`) !== null) return resolve()
const script = document.createElement("script")
script.src = src
script.async = true
document.head.appendChild(script)
script.onload = resolve
script.onerror = reject
})
Usage (async/await):
await loadCDN("https://.../script.js")
Usage (Promise):
loadCDN("https://.../script.js").then(res => {}).catch(err => {})
NOTE: there was one similar solution but it doesn't check if the script is already loaded and loads the script each time. This one checks src property.
A: I used a much less complicated version recently with jQuery:
<script src="scripts/jquery.js"></script>
<script>
var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
var $head = $("head");
for (var i = 0; i < js.length; i++) {
$head.append("<script src=\"" + js[i] + "\"></scr" + "ipt>");
}
</script>
It worked great in every browser I tested it in: IE6/7, Firefox, Safari, Opera.
Update: jQuery-less version:
<script>
var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
for (var i = 0, l = js.length; i < l; i++) {
document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"" + js[i] + "\"></scr" + "ipt>");
}
</script>
A:
does anyone have a better way?
I think just adding the script to the body would be easier then adding it to the last node on the page. How about this:
function include(url) {
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", url);
document.body.appendChild(s);
}
A: i've used yet another solution i found on the net ... this one is under creativecommons and it checks if the source was included prior to calling the function ...
you can find the file here: include.js
/** include - including .js files from JS - [email protected] - 2005-02-09
** Code licensed under Creative Commons Attribution-ShareAlike License
** http://creativecommons.org/licenses/by-sa/2.0/
**/
var hIncludes = null;
function include(sURI)
{
if (document.getElementsByTagName)
{
if (!hIncludes)
{
hIncludes = {};
var cScripts = document.getElementsByTagName("script");
for (var i=0,len=cScripts.length; i < len; i++)
if (cScripts[i].src) hIncludes[cScripts[i].src] = true;
}
if (!hIncludes[sURI])
{
var oNew = document.createElement("script");
oNew.type = "text/javascript";
oNew.src = sURI;
hIncludes[sURI]=true;
document.getElementsByTagName("head")[0].appendChild(oNew);
}
}
}
A: Just found out about a great feature in YUI 3 (at the time of writing available in preview release). You can easily insert dependencies to YUI libraries and to "external" modules (what you are looking for) without too much code: YUI Loader.
It also answers your second question regarding the function being called as soon as the external module is loaded.
Example:
YUI({
modules: {
'simple': {
fullpath: "http://example.com/public/js/simple.js"
},
'complicated': {
fullpath: "http://example.com/public/js/complicated.js"
requires: ['simple'] // <-- dependency to 'simple' module
}
},
timeout: 10000
}).use('complicated', function(Y, result) {
// called as soon as 'complicated' is loaded
if (!result.success) {
// loading failed, or timeout
handleError(result.msg);
} else {
// call a function that needs 'complicated'
doSomethingComplicated(...);
}
});
Worked perfectly for me and has the advantage of managing dependencies. Refer to the YUI documentation for an example with YUI 2 calendar.
A: I know my answer is bit late for this question, but, here is a great article in www.html5rocks.com - Deep dive into the murky waters of script loading .
In that article it is concluded that in regards of browser support, the best way to dynamically load JavaScript file without blocking content rendering is the following way:
Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:
[
'script1.js',
'script2.js',
'script3.js',
'script4.js'
].forEach(function(src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});
Now, Spec says: Download together, execute in order as soon as all download.
Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.
Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.
IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.
Everything else says: I’m your friend, we’re going to do this by the book.
Now, the full code with IE < 10 workaround:
var scripts = [
'script1.js',
'script2.js',
'script3.js',
'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];
// Watch scripts load in IE
function stateChange() {
// Execute as many scripts in order as we can
var pendingScript;
while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {
pendingScript = pendingScripts.shift();
// avoid future loading events from this script (eg, if src changes)
pendingScript.onreadystatechange = null;
// can't just appendChild, old IE bug if element isn't closed
firstScript.parentNode.insertBefore(pendingScript, firstScript);
}
}
// loop through our script urls
while (src = scripts.shift()) {
if ('async' in firstScript) { // modern browsers
script = document.createElement('script');
script.async = false;
script.src = src;
document.head.appendChild(script);
}
else if (firstScript.readyState) { // IE<10
// create a script and add it to our todo pile
script = document.createElement('script');
pendingScripts.push(script);
// listen for state changes
script.onreadystatechange = stateChange;
// must set src AFTER adding onreadystatechange listener
// else we’ll miss the loaded event for cached scripts
script.src = src;
}
else { // fall back to defer
document.write('<script src="' + src + '" defer></'+'script>');
}
}
A few tricks and minification later, it’s 362 bytes
!function(e,t,r){function n(){for(;d[0]&&"loaded"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o="onreadystatechange",f="readyState";s=r.shift();)a=e.createElement(t),"async"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write("<"+t+' src="'+s+'" defer></'+t+">"),a.src=s}(document,"script",[
"//other-domain.com/1.js",
"2.js"
])
A: There's a new proposed ECMA standard called dynamic import, recently incorporated into Chrome and Safari.
const moduleSpecifier = './dir/someModule.js';
import(moduleSpecifier)
.then(someModule => someModule.foo()); // executes foo method in someModule
A: I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the head element to get the job done. I simply created an include function (code below) to handle both script and CSS files.
This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically. It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.
function include( url, type ){
// First make sure it hasn't been loaded by something else.
if( Array.contains( includedFile, url ) )
return;
// Determine the MIME type.
var jsExpr = new RegExp( "js$", "i" );
var cssExpr = new RegExp( "css$", "i" );
if( type == null )
if( jsExpr.test( url ) )
type = 'text/javascript';
else if( cssExpr.test( url ) )
type = 'text/css';
// Create the appropriate element.
var element = null;
switch( type ){
case 'text/javascript' :
element = document.createElement( 'script' );
element.type = type;
element.src = url;
break;
case 'text/css' :
element = document.createElement( 'link' );
element.rel = 'stylesheet';
element.type = type;
element.href = url;
break;
}
// Insert it to the <head> and the array to ensure it is not
// loaded again.
document.getElementsByTagName("head")[0].appendChild( element );
Array.add( includedFile, url );
}
A: The technique we use at work is to request the javascript file using an AJAX request and then eval() the return. If you're using the prototype library, they support this functionality in their Ajax.Request call.
A: jquery resolved this for me with its .append() function
- used this to load the complete jquery ui package
/*
* FILENAME : project.library.js
* USAGE : loads any javascript library
*/
var dirPath = "../js/";
var library = ["functions.js","swfobject.js","jquery.jeditable.mini.js","jquery-ui-1.8.8.custom.min.js","ui/jquery.ui.core.min.js","ui/jquery.ui.widget.min.js","ui/jquery.ui.position.min.js","ui/jquery.ui.button.min.js","ui/jquery.ui.mouse.min.js","ui/jquery.ui.dialog.min.js","ui/jquery.effects.core.min.js","ui/jquery.effects.blind.min.js","ui/jquery.effects.fade.min.js","ui/jquery.effects.slide.min.js","ui/jquery.effects.transfer.min.js"];
for(var script in library){
$('head').append('<script type="text/javascript" src="' + dirPath + library[script] + '"></script>');
}
To Use - in the head of your html/php/etc after you import jquery.js you would just include this one file like so to load in the entirety of your library appending it to the head...
<script type="text/javascript" src="project.library.js"></script>
A: Keep it nice, short, simple, and maintainable! :]
// 3rd party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
FULL_PATH + 'plugins/script.js' // Script example
FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library
FULL_PATH + 'plugins/crypto-js/hmac-sha1.js', // CryptoJS
FULL_PATH + 'plugins/crypto-js/enc-base64-min.js' // CryptoJS
];
function load(url)
{
var ajax = new XMLHttpRequest();
ajax.open('GET', url, false);
ajax.onreadystatechange = function ()
{
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4)
{
switch(ajax.status)
{
case 200:
eval.apply( window, [script] );
console.log("library loaded: ", url);
break;
default:
console.log("ERROR: library not loaded: ", url);
}
}
};
ajax.send(null);
}
// initialize a single load
load('plugins/script.js');
// initialize a full load of scripts
if (s.length > 0)
{
for (i = 0; i < s.length; i++)
{
load(s[i]);
}
}
This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.
A: Something like this...
<script>
$(document).ready(function() {
$('body').append('<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=getCurrentPickupLocation" async defer><\/script>');
});
</script>
A: This works:
await new Promise((resolve, reject) => {
let js = document.createElement("script");
js.src = "mylibrary.js";
js.onload = resolve;
js.onerror = reject;
document.body.appendChild(js)
});
Obviously if the script you want to import is a module, you can use the import(...) function.
A: another awesome answer
$.getScript("my_lovely_script.js", function(){
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
https://stackoverflow.com/a/950146/671046
A: Dynamic module import landed in Firefox 67+.
(async () => {
await import('./synth/BubbleSynth.js')
})()
With error handling:
(async () => {
await import('./synth/BubbleSynth.js').catch((error) => console.log('Loading failed' + error))
})()
It also works for any kind of non-modules libraries, on this case the lib is available on the window.self object, the old way, but only on demand, which is nice.
Example using suncalc.js, the server must have CORS enabled to works this way!
(async () => {
await import('https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.8.0/suncalc.min.js')
.then( () => {
let times = SunCalc.getTimes(new Date(), 51.5,-0.1);
console.log("Golden Hour today in London: " + times.goldenHour.getHours() + ':' + times.goldenHour.getMinutes() + ". Take your pics!")
})
})()
https://caniuse.com/#feat=es6-module-dynamic-import
A: Here is some example code I've found... does anyone have a better way?
function include(url)
{
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", url);
var nodes = document.getElementsByTagName("*");
var node = nodes[nodes.length -1].parentNode;
node.appendChild(s);
}
A: There are scripts that are designed specifically for this purpose.
yepnope.js is built into Modernizr, and lab.js is a more optimized (but less user friendly version.
I wouldn't reccomend doing this through a big library like jquery or prototype - because one of the major benefits of a script loader is the ability to load scripts early - you shouldn't have to wait until jquery & all your dom elements load before running a check to see if you want to dynamically load a script.
A: I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/
var _rmod = _rmod || {}; //require module namespace
_rmod.on_ready_fn_stack = [];
_rmod.libpath = '';
_rmod.imported = {};
_rmod.loading = {
scripts: {},
length: 0
};
_rmod.findScriptPath = function(script_name) {
var script_elems = document.getElementsByTagName('script');
for (var i = 0; i < script_elems.length; i++) {
if (script_elems[i].src.endsWith(script_name)) {
var href = window.location.href;
href = href.substring(0, href.lastIndexOf('/'));
var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);
return url.substring(href.length+1, url.length);
}
}
return '';
};
_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark the root directory of your library, any library
_rmod.injectScript = function(script_name, uri, callback, prepare) {
if(!prepare)
prepare(script_name, uri);
var script_elem = document.createElement('script');
script_elem.type = 'text/javascript';
script_elem.title = script_name;
script_elem.src = uri;
script_elem.async = true;
script_elem.defer = false;
if(!callback)
script_elem.onload = function() {
callback(script_name, uri);
};
document.getElementsByTagName('head')[0].appendChild(script_elem);
};
_rmod.requirePrepare = function(script_name, uri) {
_rmod.loading.scripts[script_name] = uri;
_rmod.loading.length++;
};
_rmod.requireCallback = function(script_name, uri) {
_rmod.loading.length--;
delete _rmod.loading.scripts[script_name];
_rmod.imported[script_name] = uri;
if(_rmod.loading.length == 0)
_rmod.onReady();
};
_rmod.onReady = function() {
if (!_rmod.LOADED) {
for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){
_rmod.on_ready_fn_stack[i]();
});
_rmod.LOADED = true;
}
};
//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.
var require = function(script_name) {
var np = script_name.split('.');
if (np[np.length-1] === '*') {
np.pop();
np.push('_all');
}
script_name = np.join('.');
var uri = _rmod.libpath + np.join('/')+'.js';
if (!_rmod.loading.scripts.hasOwnProperty(script_name)
&& !_rmod.imported.hasOwnProperty(script_name)) {
_rmod.injectScript(script_name, uri,
_rmod.requireCallback,
_rmod.requirePrepare);
}
};
var ready = function(fn) {
_rmod.on_ready_fn_stack.push(fn);
};
// ----- USAGE -----
require('ivar.util.array');
require('ivar.util.string');
require('ivar.net.*');
ready(function(){
//do something when required scripts are loaded
});
A: I am lost in all these samples but today I needed to load an external .js from my main .js and I did this:
document.write("<script src='https://www.google.com/recaptcha/api.js'></script>");
A: Here is a simple one with callback and IE support:
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
//jQuery loaded
console.log('jquery loaded');
});
A: Here a simple example for a function to load JS files. Relevant points:
*
*you don't need jQuery, so you may use this initially to load also the jQuery.js file
*it is async with callback
*it ensures it loads only once, as it keeps an enclosure with the record of loaded urls, thus avoiding usage of network
*contrary to jQuery $.ajax or $.getScript you can use nonces, solving thus issues with CSP unsafe-inline. Just use the property script.nonce
var getScriptOnce = function() {
var scriptArray = []; //array of urls (closure)
//function to defer loading of script
return function (url, callback){
//the array doesn't have such url
if (scriptArray.indexOf(url) === -1){
var script=document.createElement('script');
script.src=url;
var head=document.getElementsByTagName('head')[0],
done=false;
script.onload=script.onreadystatechange = function(){
if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
done=true;
if (typeof callback === 'function') {
callback();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
scriptArray.push(url);
}
};
head.appendChild(script);
}
};
}();
Now you use it simply by
getScriptOnce("url_of_your_JS_file.js");
A: For those of you, who love one-liners:
import('./myscript.js');
Chances are you might get an error, like:
Access to script at 'http://..../myscript.js' from origin
'http://127.0.0.1' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
In which case, you can fallback to:
fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());
A: In as much as I love how handy the JQuery approach is, the JavaScript approach isn't that complicated but just require little tweaking to what you already use...
Here is how I load JS dynamically(Only when needed), and wait for them to load before executing the script that depends on them.
JavaScript Approach
//Create a script element that will load
let dynamicScript = document.createElement('script');
//Set source to the script we need to load
dynamicScript.src = 'linkToNeededJsFile.js';
//Set onload to callback function that depends on this script or do inline as shown below
dynamicScript.onload = () => {
//Code that depends on the loaded script should be here
};
//append the created script element to body element
document.body.append(dynamicScript);
There are other ways approach one could accomplish this with JS but, I prefer this as it's require the basic JS knowledge every dev can relate.
Not part of the answer but here is the JQuery version I prefer with projects that already include JQuery:
$.getScript('linkToNeededJsFile.js', () => {
//Code that depends on the loaded script should be here
});
More on the JQuery option here
A: This function uses memorization. And could be called many times with no conflicts of loading and running the same script twice. Also it's not resolving sooner than the script is actually loaded (like in @radulle answer).
const loadScript = function () {
let cache = {};
return function (src) {
return cache[src] || (cache[src] = new Promise((resolve, reject) => {
let s = document.createElement('script');
s.defer = true;
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.append(s);
}));
}
}();
Please notice the parentheses () after the function expression.
Parallel loading of scripts:
Promise.all([
loadScript('/script1.js'),
loadScript('/script2.js'),
// ...
]).then(() => {
// do something
})
You can use the same method for dynamic loading stylesheets.
A: all the major javascript libraries like jscript, prototype, YUI have support for loading script files. For example, in YUI, after loading the core you can do the following to load the calendar control
var loader = new YAHOO.util.YUILoader({
require: ['calendar'], // what components?
base: '../../build/',//where do they live?
//filter: "DEBUG", //use debug versions (or apply some
//some other filter?
//loadOptional: true, //load all optional dependencies?
//onSuccess is the function that YUI Loader
//should call when all components are successfully loaded.
onSuccess: function() {
//Once the YUI Calendar Control and dependencies are on
//the page, we'll verify that our target container is
//available in the DOM and then instantiate a default
//calendar into it:
YAHOO.util.Event.onAvailable("calendar_container", function() {
var myCal = new YAHOO.widget.Calendar("mycal_id", "calendar_container");
myCal.render();
})
},
// should a failure occur, the onFailure function will be executed
onFailure: function(o) {
alert("error: " + YAHOO.lang.dump(o));
}
});
// Calculate the dependency and insert the required scripts and css resources
// into the document
loader.insert();
A: I have tweaked some of the above post with working example.
Here we can give css and js in same array also.
$(document).ready(function(){
if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) { if (this[i] === obj) return true; }
return false;
};
};
/* define object that will wrap our logic */
var jsScriptCssLoader = {
jsExpr : new RegExp( "js$", "i" ),
cssExpr : new RegExp( "css$", "i" ),
loadedFiles: [],
loadFile: function (cssJsFileArray) {
var self = this;
// remove duplicates with in array
cssJsFileArray.filter((item,index)=>cssJsFileArray.indexOf(item)==index)
var loadedFileArray = this.loadedFiles;
$.each(cssJsFileArray, function( index, url ) {
// if multiple arrays are loaded the check the uniqueness
if (loadedFileArray.contains(url)) return;
if( self.jsExpr.test( url ) ){
$.get(url, function(data) {
self.addScript(data);
});
}else if( self.cssExpr.test( url ) ){
$.get(url, function(data) {
self.addCss(data);
});
}
self.loadedFiles.push(url);
});
// don't load twice accross different arrays
},
addScript: function (code) {
var oNew = document.createElement("script");
oNew.type = "text/javascript";
oNew.textContent = code;
document.getElementsByTagName("head")[0].appendChild(oNew);
},
addCss: function (code) {
var oNew = document.createElement("style");
oNew.textContent = code;
document.getElementsByTagName("head")[0].appendChild(oNew);
}
};
//jsScriptCssLoader.loadFile(["css/1.css","css/2.css","css/3.css"]);
jsScriptCssLoader.loadFile(["js/common/1.js","js/2.js","js/common/file/fileReader.js"]);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "192"
} |
Q: In C++ can constructor and destructor be inline functions? VC++ makes functions which are implemented within the class declaration inline functions.
If I declare a class Foo as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?
class Foo
{
int* p;
public:
Foo() { p = new char[0x00100000]; }
~Foo() { delete [] p; }
};
{
Foo f;
(f);
}
A: Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the "inline" keyword.
In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules.
A: Putting the function definition in the class body is equivalent to marking a function with the inline keyword. That means the function may or may not be inlined by the compiler. So I guess the best answer would be "maybe"?
A: The short answer is yes. Any function can be declared inline, and putting the function body in the class definition is one way of doing that. You could also have done:
class Foo
{
int* p;
public:
Foo();
~Foo();
};
inline Foo::Foo()
{
p = new char[0x00100000];
}
inline Foo::~Foo()
{
delete [] p;
}
However, it's up to the compiler if it actually does inline the function. VC++ pretty much ignores your requests for inlining. It will only inline a function if it thinks it's a good idea. Recent versions of the compiler will also inline things that are in separate .obj files and not declared inline (e.g. from code in different .cpp files) if you use link time code generation.
You could use the __forceinline keyword to tell the compiler that you really really mean it when you say "inline this function", but it's usally not worth it. In many cases, the compiler really does know best.
A: To the same extent that we can make any other function inline, yes.
A: To inline or not is mostly decided by your compiler. Inline in the code only hints to the compiler.
One rule that you can count on is that virtual functions will never be inlined. If your base class has virtual constructor/destructor yours will probably never be inlined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "83"
} |
Q: Audio/Video Remote Control Profile (AVRCP) on Windows Mobile Is there a general way to handle Bluetooth Audio/Video Remote Control Profile (AVRCP) events on a WM device? I'm especially interested in a Compact Framework way, but I would be happy with just a simple P/Invoke API.
Update.
I've read MSDN articles on this topic, but I still have no idea on how to facilitate this knowledge. There are no samples. Can anyone help me?
A: Here is the MSDN page about AVRCP
Microsofts solution uses the Audio/Video Control Transport Control Protocol (AVCTP). The Microsoft component is an extension layer to the L2CAP layer in the Microsoft Bluetooth Protocol Stack.
The following list shows the supported commands:
*
*Play
*Stop
*Pause
*Forward
*Backward
Other Bluetooth profiles can be found on MSDN as well.
Hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Batch file to "Script" a Database Is it possible to somehow use a .bat file to script the schema and/or content of a SQL Server database?
I can do this via the wizard, but would like to streamline the creation of this file for source control purposes.
I would like to avoid the use of 3rd party tools, just limiting myself to the tools that come with SQL Server.
A: There is a free tool called SubCommander that is a part of the open source SubSonic software. I have successfully used this tool myself to create both schema and data "dumps" each night.
You can script out your schema and
data (and then version it in your
favorite source control system) using
SubCommander. Simply use the command
"version" and tell SubCommander where
to put the data:
sonic.exe version /out Scripts
This will output a script file (.sql)
to the local scripts directory of your
project
You can also try using the Microsoft SQL Server Database Publishing wizard, although i am not sure that you can use it in a bat file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Mocking and IQueryable I've ran into a problem while trying to test following IRepository based on NHibernate:
public class NHibernateRepository<T>: Disposable, IRepository<T>
where T : IdentifiableObject
{
...
public IQueryable<T> Query()
{
return NHibernateSession.Linq<T>();
}
}
How on the Hell to mock returning IQueryable<T> out in the way that it returns given collection in exchange certain expression. I feel I have some misunderstanding of IQueryable<T>...
A: In Moq it would be:
mockRepository.Expect( r => r.Query() ).Returns( myEnumerable.AsQueriable() );
In RhinoMocks it would be:
Expect.Call( repository.Query() ).Return( myEnumerable.AsQueriable() );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Represent Ordering in a Relational Database I have a collection of objects in a database. Images in a photo gallery, products in a catalog, chapters in a book, etc. Each object is represented as a row. I want to be able to arbitrarily order these images, storing that ordering in the database so when I display the objects, they will be in the right order.
For example, let's say I'm writing a book, and each chapter is an object. I write my book, and put the chapters in the following order:
Introduction, Accessibility, Form vs. Function, Errors, Consistency, Conclusion, Index
It goes to the editor, and comes back with the following suggested order:
Introduction, Form, Function, Accessibility, Consistency, Errors, Conclusion, Index
How can I store this ordering in the database in a robust, efficient way?
I've had the following ideas, but I'm not thrilled with any of them:
*
*Array. Each row has an ordering ID, when order is changed (via a removal followed by an insertion), the order IDs are updated. This makes retrieval easy, since it's just ORDER BY, but it seems easy to break.
// REMOVAL
UPDATE ... SET orderingID=NULL WHERE orderingID=removedID
UPDATE ... SET orderingID=orderingID-1 WHERE orderingID > removedID
// INSERTION
UPDATE ... SET orderingID=orderingID+1 WHERE orderingID > insertionID
UPDATE ... SET orderID=insertionID WHERE ID=addedID
*Linked list. Each row has a column for the id of the next row in the ordering. Traversal seems costly here, though there may by some way to use ORDER BY that I'm not thinking of.
*Spaced array. Set the orderingID (as used in #1) to be large, so the first object is 100, the second is 200, etc. Then when an insertion happens, you just place it at (objectBefore + objectAfter)/2. Of course, this would need to be rebalanced occasionally, so you don't have things too close together (even with floats, you'd eventually run into rounding errors).
None of these seem particularly elegant to me. Does anyone have a better way to do it?
A: An other alternative would be (if your RDBMS supports it) to use columns of type array. While this breaks the normalization rules, it can be useful in situations like this. One database which I know about that has arrays is PostgreSQL.
A: The acts_as_list mixin in Rails handles this basically the way you outlined in #1. It looks for an INTEGER column called position (of which you can override to name of course) and using that to do an ORDER BY. When you want to re-order things you update the positions. It has served me just fine every time I've used it.
As a side note, you can remove the need to always do re-positioning on INSERTS/DELETES by using sparse numbering -- kind of like basic back in the day... you can number your positions 10, 20, 30, etc. and if you need to insert something in between 10 and 20 you just insert it with a position of 15. Likewise when deleting you can just delete the row and leave the gap. You only need to do re-numbering when you actually change the order or if you try to do an insert and there is no appropriate gap to insert into.
Of course depending on your particular situation (e.g. whether you have the other rows already loaded into memory or not) it may or may not make sense to use the gap approach.
A: If the objects aren't heavily keyed by other tables, and the lists are short, deleting everything in the domain and just re-inserting the correct list is the easiest. But that's not practical if the lists are large and you have lots of constraints to slow down the delete. I think your first method is really the cleanest. If you run it in a transaction you can be sure nothing odd happens while you're in the middle of the update to screw up the order.
A: Just a thought considering option #1 vs #3: doesn't the spaced array option (#3) only postpone the problem of the normal array (#1)? Whatever algorithm you choose, either it's broken, and you'll run into problems with #3 later, or it works, and then #1 should work just as well.
A: I did this in my last project, but it was for a table that only occasionally needed to be specifically ordered, and wasn't accessed too often. I think the spaced array would be the best option, because it reordering would be cheapest in the average case, just involving a change to one value and a query on two).
Also, I would imagine ORDER BY would be pretty heavily optimized by database vendors, so leveraging that function would be advantageous for performance as opposed to the linked list implementation.
A: Use a floating point number to represent the position of each item:
Item 1 -> 0.0
Item 2 -> 1.0
Item 3 -> 2.0
Item 4 -> 3.0
You can place any item between any other two items by simple bisection:
Item 1 -> 0.0
Item 4 -> 0.5
Item 2 -> 1.0
Item 3 -> 2.0
(Moved item 4 between items 1 and 2).
The bisection process can continue almost indefinitely due to the way floating point numbers are encoded in a computer system.
Item 4 -> 0.5
Item 1 -> 0.75
Item 2 -> 1.0
Item 3 -> 2.0
(Move item 1 to the position just after Item 4)
A: Since I've mostly run into this with Django, I've found this solution to be the most workable. It seems that there isn't any "right way" to do this in a relational database.
A: I'd do a consecutive number, with a trigger on the table that "makes room" for a priority if it already exists.
A: I had this problem as well. I was under heavy time pressure (aren't we all) and I went with option #1, and only updated rows that changed.
If you swap item 1 with item 10, just do two updates to update the order numbers of item 1 and item 10. I know it is algorithmically simple, and it is O(n) worst case, but that worst case is when you have a total permutation of the list. How often is that going to happen? That's for you to answer.
A: I had the same issue and have probably spent at least a week concerning myself about the proper data modeling, but I think I've finally got it. Using the array datatype in PostgreSQL, you can store the primary key of each ordered item and update that array accordingly using insertions or deletions when your order changes. Referencing a single row will allow you to map all your objects based on the ordering in the array column.
It's still a bit choppy of a solution but it will likely work better than option #1, since option 1 requires updating the order number of all the other rows when ordering changes.
A: Scheme #1 and Scheme #3 have the same complexity in every operation except INSERT writes. Scheme #1 has O(n) writes on INSERT and Scheme #3 has O(1) writes on INSERT.
For every other database operation, the complexity is the same.
Scheme #2 should not even be considered because its DELETE requires O(n) reads and writes. Scheme #1 and Scheme #3 have O(1) DELETE for both read and write.
New method
If your elements have a distinct parent element (i.e. they share a foreign key row), then you can try the following ...
Django offers a database-agnostic solution to storing lists of integers within CharField(). One drawback is that the max length of the stored string can't be greater than max_length, which is DB-dependent.
In terms of complexity, this would give Scheme #1 O(1) writes for INSERT, because the ordering information would be stored as a single field in the parent element's row.
Another drawback is that a JOIN to the parent row is now required to update ordering.
https://docs.djangoproject.com/en/dev/ref/validators/#django.core.validators.validate_comma_separated_integer_list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Source Control in Visual Studio Isolated Shell I am developing an Isolated Shell that caters to "designers/special content creators" performing specific tasks, using the Shell. As they operate on files, they need to be able to use TFS for source control. This is mainly due to the fact that Developers will also operate on the same files from TFS but using Visual studio 2008.
After looking and searching I still could not find Team Explorer to be available to Shell.
Asking on MSDN forums, lead me to the answer that "this is not supported yet in the Isolated Shell". Well, then the whole point of giving away a shell is not justified, if you want to use a source control system for your files. The idea is not to recreate everything and develop tool windows etc using the TFS provider API.
The Visual Studio Extensibility book by Keyven Nayyeri has an example, which only goes so far into this problem of adding a sc provider.
Has anyone worked on developing Visual Studio 2008 Isolated Shell applications/environment? Please provide comments, questions - anything that you have to share apart from the following threads, which I've already participated in.
Threads from MSDN forums:
*
*Team Explorer for Isolated Shell
*Is it possible to use Team Explorer in VS Shell Isolated?
Thanks for your answer. Yes you are right, we will acquire CALs for users without having to buy them Visual Studio, that's the direction we will be taking.
But I am yet to figure out how to make Team Explorer available to such users, inside Shell. So I am looking to find out the technical details of how that can be done.
I mean, I have a user, he installs my VS Shell application, he has no VStudio Team system on his machine. Now if I acquire CAL for TFS and install Team Explorer, do you think it will be automatically available in the VS Shell app?
Any ideas? have you worked on making this happen?
Thanks
A: It sounds like you are trying to allow the "special content creators" save files in TFS Source Control without having to buy them a license to a Visual Studio Team Edition -- correct me if I'm wrong.
If that's the case, unfortunately I believe that you can't quite do that. Your users still need a Client Access License ("CAL") to access TFS.
I think that you can acquire just CALs for your users without having to buy Visual Studio for them (I presume for less than a full blown Visual Studio would cost). At that point, you can just distribute to them the Team Explorer, which is a VS shell with nothing but TFS access components. That is available in your TFS server media.
I found this via Google. You might want to review it to decide your best options:
Visual Studio Team System 2008 Licensing White Paper
The only exception to the CAL rules I'm aware of is access to Work Items. Assuming properly licensed servers, anyone in your organization can create new Work Items or view and update existing ones created by them, using the Work Item Web Access component.
A: Just stumbled on this question, it might still be relevant to you.
You have the option of including the AnkhSVN (http://ankhsvn.open.collab.net/) packages and load it into your Isolated Shell. While there are some issues around it, with Subversion support, you could use SvnBridge to access TFS repositories. This might bring you a little bit closer to the process you are trying to achieve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: sleep() silently hogs CPU I'm running Apache on Linux within VMWare.
One of the PHP pages I'm requesting does a sleep(), and I find that if I attempt to request a second page whilst the first page is sleep()'ing, the second page hangs, waiting for the sleep() from the first page to finish.
Has anyone else seen this behaviour?
I know that PHP isn't multi-threaded, but this seems like gross mishandling of the CPU.
Edit: I should've mentioned that the CPU usage doesn't spike. What I mean by CPU "hogging" is that no other PHP page seems able to use the CPU whilst the page is sleep()'ing.
A: What this probably means is that your Apache is only using 1 child process.
Therefore:
The 1 child process is handling a request (in this case sleeping but it could be doing real work, Apache can't tell the difference), so when a new request comes it, it will have to wait until the first process is done.
The solution would be to increase the number of child processes Apache is allowed to spawn (MaxClients directive if you're using the prefork MPM), simply remove the sleep() from the PHP script.
Without exactly knowing what's going on in your script it's hard to say, but you can probably get rid of the sleep().
A: It could be that the called page opens a session and then doesn't commit it, in this case see this answer for a solution.
A: Are you actually seeing the CPU go to 100% or just that no other pages are being served? How many apache-instances are you runnning? Are they all stopping when you run sleep() in of of the threads?
PHP's sleep() function essentially runs through an idle loop for n seconds. It doesn't release any memory, but it should not increase CPU load significantly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to address semantic issues with tag-based web sites Tag-based web sites often suffer from the delicacy of language such as synonyms, homonyms, etc. For programmers looking for information, say on Stack Overflow, concrete examples are:
*
*Subversion or SVN (or svn, with case-sensitive tags)
*.NET or Mono
*[Will add more]
The problem is that we do want to preserve our delicacy of language and make the machine deal with it as good as possible.
A site like del.icio.us sees its tag base grow a lot, thus probably hindering usage or search. Searching for SVN-related entries will probably list a majority of entries with both subversion and svn tags, but I can think of three issues:
*
*A search is incomplete as many entries may not have both tags (which are 'synonyms').
*A search is less useful as Q/A often lead to more Qs! Notably for newbies on a given topic.
*Tagging a question (note: or an answer separately, sounds useful) becomes philosophical: 'Did I Tag the Right Way?'
One way to address these issues is to create semantic links between tags, so that subversion and SVN are automatically bound by the system, not by poor users.
Is it an approach that sounds good/feasible/attractive/useful? How to implement it efficiently?
A: Recognizing synonyms and semantic connections is something that humans are good at; a solution to organizing an open-ended taxonomy like what SO is featuring would probably be well served by finding a way to leave the matching to humans.
One general approach: someone (or some team) reviews new tags on a daily basis. New synonyms are added to synonym groups. Searches hit synonym groups (or, more nuanced, hit either literal matches or synonym group matches according to user preference).
This requires support for synonym groups on the back end (work for the dev team). It requires a tag wrangler or ten (work for the principals or for trusted users). It doesn't require constant scaling, though—the rate at which the total tag pool grows will likely (after the initial Here Comes Everybody bump of the open beta) will in all likelihood decrease over time, as any organic lexicon's growth-rate does.
Synonymy strikes me as the go-to issue. Hierarchical mapping is an ambitious and more complicated issue; it may be worth it or it may not be, but given the relative complexity of defining the hierarchy it'd probably be better left as a Phase 2 to any potential synonym project's Phase 1.
A: The way the software on blogspot.com is set up, is that there is an ajax-autocomplete-thingie on the box where you write the name of the tags. This searches all your previous posts for tags that start with the same letters. At least that way you catch different casings and spellings (but not synonyms).
A: I completely agree. The mass of tags that have currently. I don't participate in other tagged based sites. However having a hierarchy of tags would be very helpful, instead of ruby rails ruby-on-rails rubyonrails etc...
A: How would the system know which tags to semantically link? Would it keep an ever-growing map of tags? I can't see that working. What if someone typed sbversion instead? How would that get linked?
I think that asking the user when they submit tags could work. For example, "You've entered the following tags: sbversion, pascal and bindings. Did you mean, "Subversion", "Pascal" and "Bindings"?
Obviously the system would have to have a fairly smart matching system for that to work. Doing it this way would be extra input for the user (which'd probably annoy them) but the human input would, if done correctly, make for less duplicate tags.
In fact, having said all that, the system could use the results of the user's input as a basis for automatic tag matching. From the previous example, someone creates a tag of "sbversion" and when prompted changes it to "Subversion" - the system could learn that and do it automatically next time.
A: Part of the issue you're looking at is that English is rife with synonyms - are the following different: build-management, subversion, cvs, source-control?
Maybe, maybe not. Having a system, like the one [now] in use on SO that brings up the tag you probably meant is extremely helpful. But it doesn't stop people from bulling-through the tagging process.
Maybe you could refuse to accept "new" tags without a user-interaction? Before you let 'sbversion' go in, force a spelling check?
This is definitely an interesting problem. I asked an open question similar to this on my blog last year. A couple of the responses were quite insightful.
A: Tags are basically our admission that search algorithms aren't up to snuff. If we can get a computer to be smart enough to identify that things tagged "Subversion" have similar content to things tagged "svn", presumably we can parse the contents, so why not skip tags altogether, and match a search term directly to the content (i.e., autotagging, which is basically mapping keywords to results)?!
A: The problem is to make the search engine use the fact that 'subversion' and 'svn' are very similar to the point that they mean the same 'thing'.
It might be attractive to compute a simple similarity between tags based on frequency: 'subversion' and 'svn' appear very often together, so requesting 'svn' would return SVN-related questions, but also the rare questions only tagged 'subversion' (and vice versa). However, 'java' and 'c#' also appear often together, but for very different reasons (they are not synonyms). So similarity based on frequency is out.
An answer to this problem might be a mix of mechanisms, as the ones suggested in this Q/A thread:
*
*Filtering out typos by suggesting tags when the user inputs them.
*Maintaining a user-generated map of synonyms. This map may not be that big if it just targets synonyms.
*Allowing multi-tag search, such that the user can put 'subversion svn' or 'subversion && svn' (well, from programmers to programmers) in the search box and get both. This would be quite practical as many users may actually try such approach when they do not know which term is the most meaningful.
@Nick: Agreed. The question is not meant to argue against tags. Tags have great potential, but users will face a growing issue if one cannot search 'across' tags.
@Steve: Maintaining an ever-growing map of tags is definitely not practical. As SO is accumulating an ever-growing bag of tags, how could we shade some light on this bag to make search of Q/A tags even more useful, in a convenient way?
@Espo: 'Ajax-powered' tag suggestions based on existing tags is apparently available on SO when creating a question. This is by the way very helpful to choose tags and appropriate spelling (avoiding the 'subversion' vs. 'sbversion' issue from Steve).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Preventing a visitor from saving an image from my site What are some effective strategies for preventing the use of my proprietary images?
I'm talking about saving them, direct linking to them etc...
Presently I have a watermark on the image, but I'd rather not.
.NET platform preferred, but if there's a strategy that's on another platform that integrates with my existing application that'd be a bonus.
A: using JavaScript to override the click event is the most common I have seen...
see: http://pubs.logicalexpressions.com/pub0009/LPMArticle.asp?ID=41
A: I figure I might as well put in my two cents.
None of the above methods will work with perhaps the exception of a watermark.
Wherever I go, I can hit print screen on my computer and paste into a graphics editor, and with a little cropping, I have your image.
The only way to overcome the watermark issue would be to use photoshop tools to remove the watermark. At this point, i think most people would just give up and pay you for your content or at a minimum go rip off somebody else.
A: It's not possible to make it "impossible" to download. When a user visits your site you're sending them the pictures. The user will have a copy of that image in the browsers cache and he'd be able to access it even after he leaves the site ( depending on the browser, of course ). Your only real option is to watermark them :O
A: Short answer: you can't. Whatever you display to a user is going to be available to them. You can watermark it, blur it, or offer a low-res version of it, but the bottom line is that whatever images are displayed in the user's browser are going to be available to them in some way.
A: It's just not possible. There is always the PrintScreen button.
Whatever is displayed, can be captured.
A: I would watermark them, and reduce the resolution, of the actual files, instead of doing it through an application on the user's end.
A: unfortunately you can always screen grab the browser and crop the image out, not perfect but it circumvents almost every solution posted here :(
A: Another approach I've seen that's still entirely vulnerable to screen grabs but does make right-click and cache searching sufficiently annoying is to break the image up into many little images and display them on your page tiled together to appear as though they were a single image. But as everyone has said, if they can see it, they can grab it.
A: You could embed each image inside of a flash application, then the browser wouldn't know how to 'save' the image and wouldn't store the raw jpg in the cache folder either. They could still just press the print screen key to get a copy of the image, but it would probably be enough to stop most visitors.
A: Response.WriteBinary(), embedded flash, JavaScript hacks, hidden divs.
Over the years I have seen and tried every possible way to secure an image and I have come to one conclusion: If it can be seen online; it can be taken, my friend.
So, what you really should consider what the final goal of this action would really be. Prevent piracy? If a gross and oversized watermark is not your style, you can always embed hidden data (Apress had an article that looked promising on digital steganography) in images to identify them as your own later. You might only offer reduced or lower quality images.
Flickr takes the approach of placing a transparent gif layer on top of the image so if you are not logged in and right click you get their ever awesome spaceball.gif. But nothing can prevent a screenshot other than, well, just not offering the picture.
If the music industry could get you to listen to all of your music without copying or owning files they would. If television could broadcast and be certain nobody could store a copy of the cast, they probably would as well. It's the unfortunate part of sharing media with the public. The really good question here is how you can protect your material WITHOUT getting in the way of respectable users from consuming your images. Put on too much protection and nobody will go to your site/use your software (Personally if you try to disable my mouse I'll go from good user to bad nearly instantly).
A: Realistically you can't, unless you don't want them to see it in the first place. You could use some javascript to catch the right mouse button click, but that's really about it.
Another thought, you could possibly embed it in flash, but again, they could just take a screenshot.
A: Sorry. That's impossible. All you can do is make it inconvenient a la flickr.
A:
It's just not possible. There is always the PrintScreen button.
I remember testing ImageFreeze years ago. It used a Java applet to fetch and display images. The image data and connection was encrypted and the unencrypted image wasn't stored in a temp folder or even in Java's cache.
Also, the applet constantly cleared the windows clipbrd so Print Screen didn't work.
It worked pretty good, but it had some faults.
Besides requiring Java, the JS that embedded the applet (and maybe the applet itself) was setup to not load properly in any browser that didn't give access to the windows clipbrd. This meant that it only worked in IE and only on windows.
Also, the interval the applet used to clear the clipbrd could be beaten with a really fast Print Screen and ctrl+v into Gimp. Printing the screen in other ways would work too.
Finally, Jad could decompile the applet and all/most of its files. So, if you really wanted the pics, you could poke around in the source to figure out how they did it.
In short, you can go out of your way to stop a lot of people, but usability goes down the drain and there will always be a way to get the image if the visitor can see it.
A: Anything you send to the client is, like, on the client. Not much you can do about it besides making somewhere between "sorta hard" and "quite hard" to save the image.
A:
I must say in the begining that it is almost impossible to stop the
images or text being copied, but making it difficult will prevent most
of the users to steal content.. In this article I will give a easier
but effective way of protecting images with html/css. We will take a
very simple way for this… Firstly in a div we will place the image
with a given height and width. (Say 200 X 200)
Now we can place another transparent image with same height and
width and give it a margine of -200. So that it will overlap the
actual image. And when the user will try to copy this, they will end
up with the transparent gif only…
<div style=”float: left;”>
<img src=”your-image.jpg” style=”width: 200px;height: 200px;”/>
<img src=”the-dummy-image.png” style=”border: 0px solid #000; width: 200px; height: 250px; margin-left: -200px; ” />
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I access Excel data source from an SSIS package deployed on a 64-bit server? I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files.
So far I have this:
DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION
LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data
Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties=
""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E
This gives me the error: Option "Properties=Excel 8.0;HDR=Yes" is not valid.
I've tried a few variations with the Quotation marks but have not been able to get it right yet.
Does anyone know how to fix this?
UPDATE:
Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version.
A: This step-by-step example is for others who might stumble upon this question. This example uses SSIS 2005 and uses SQL Server 2005 64-bit edition server to run the job.
The answer here concentrates only on fixing the error message mentioned in the question. The example will demonstrate the steps to recreate the issue and also the cause of the issue followed by how to fix it.
NOTE: I would recommend using the option of storing the package configuration values in database or using indirect XML configuration with the help of Environment Variables. Also, the steps to create Excel file would be done using a template which would then archived by moving to a different folder. These steps are not discussed in this post. As mentioned earlier, the purpose of this post is to address the error.
Let’s proceed with the example. I have also blogged about this answer, which can be found in this link. It is the same answer.
Create an SSIS package (Steps to create an SSIS package). This example uses BIDS 2005. I have named the package in the format YYYYMMDD_hhmm in the beginning followed by SO stands for Stack Overflow, followed by the SO question id, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have a Data Sources named Adventure Works. I will be using Adventure Works data source, which points to AdventureWorks database downloaded from this link. The example uses SQL Server 2008 R2 database. Refer screenshot #1.
In the AdventureWorks database, create a stored procedure named dbo.GetCurrency using the below given script.
CREATE PROCEDURE [dbo].[GetCurrency]
AS
BEGIN
SET NOCOUNT ON;
SELECT
TOP 10 CurrencyCode
, Name
, ModifiedDate
FROM Sales.Currency
ORDER BY CurrencyCode
END
GO
On the package’s Connection Manager section, right-click and select New Connection From Data Source. On the Select Data Source dialog, select Adventure Works and click OK. You should now see the Adventure Works data source under the Connection Managers section.
On the package’s Connection Managers section, right-click again but this time select New Connection…. This is to create the Excel connection. On the Add SSIS Connection Manager, select EXCEL. On the Excel Connection Manager, enter the path C:\Temp\Template.xls. When we deploy it to the server, we will change this path. I have selected Excel version Microsoft Excel 97-2005 and chose to leave the checkbox First row has column names checked so that the create the Excel file is created column headers. Click OK. Rename the Excel connection to Excel, just to keep it simple. Refer screenshots #2 - #7.
On the package, create the following variable. Refer screenshot #8.
*
*SQLGetData: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value EXEC dbo.GetCurrency
Screenshot #9 shows the output of the stored procedure execution statement EXEC dbo.GetCurrency
On the package’s Control Flow tab, place a Data Flow task and name it as Export to Excel. Refer screenshot #10.
Double-click on the Data Flow Task to switch to the Data Flow tab.
On the Data Flow tab, place an OLE DB Source to connect to the SQL Server data to fetch the data from the stored procedure and name it as SQL. Double-click on the OLE DB Source to bring up the OLE DB Source Editor. On the Connection Manager section, select Adventure Works from the OLE DB connection manager, select SQL command from variable from Data access mode and select the variable User::SQLGetData from the Variable name drop down. On the Columns section, make sure the column names are mapped correctly. Click OK to close the OLE DB Source Editor. Refer screenshots #11 and #12.
On the Data Flow tab, place an Excel Destination to insert the data into the Excel file and name it as Excel. Double-click on the Excel Destination to open the Excel Destination Editor. On the Connection Manager section, select Excel from the OLE DB connection manager and select Table or view from Data access mode. At this point, we don’t have an Excel because while creating the Excel connection manager, we simply specified the path but never created the file. Hence, there won’t be any values in the drop down Name of the Excel sheet. So, click the New… button (the second New one) to create a new Excel sheet. On the Create Table window, BIDS automatically provide a create sheet based on the incoming data source. You can change the values according to your preferences. I will simply click OK by retaining the default value. The name of the sheet will be populated in the drop down Name of the Excel sheet. The name of the sheet is taken from the task name, here in this case the Excel Destination, which we have named it as Excel. On the Mappings section, make sure the column names are mapped correctly. Click OK to close the Excel Destination Editor. Refer screenshots #13 - #16.
Once the data flow task is configured, it should look like as shown in screenshot #17.
Execute the package by pressing F5. Screenshots #18 - #21 show the successful execution of the package in both Control Flow and Data Flow Task. Also, the file is generated in the path C:\Temp\Template.xls provided in the Excel connection and the data shown in the stored procedure execution output matches with the data written to the file.
The package developed on my local machine in the folder path C:\Learn\Learn.VS2005\Learn.SSIS. Now, we need to deploy the files on to the Server that hosts the 64-bit version of the SQL Server to schedule a job. So, the folder on the server would be D:\SSIS\Practice. Copy the package file (.dtsx) from the local machine and paste it in the server folder. Also, in order for the package to run correctly, we need to have the Excel spreadsheet present on the server. Otherwise, the validation will fail. Usually, I create a Template folder that will contain the empty Excel spreadsheet file that matches the output. Later, during run time I will change the Excel output path to a different location using package configuration. For this example, I am going to keep it simple. So, let’s copy the Excel file generated in the local machine in the path C:\Temp\Template.xls to the server location D:\SSIS\Practice. I want the SQL job to generate the file in the name Currencies.xls. So, rename the file Template.xls to Currencies.xls. Refer screenshot #22.
To show that I am indeed going to run the job on the server in a 64-bit edition of SQL Server, I executed the command SELECT @@version on the SQL Server and screenshot #23 shows the results.
We will use Execute Package Utility (dtexec.exe) to generate the command line parameters. Log into the server which will run the SSIS package in an SQL job. Double-click on the package file, this will bring the Execute Package Utility. On the General section, select File system from Package source. Click on the Ellipsis and browse to the package path. On the Connection Managers section, select Excel and change the path inside the Excel file from C:\Temp\Template.xls to D:\SSIS\Practice\Currencies.xls. The changes made in the Utility will generate a command line accordingly on the Command Line section. On the Command Line section, copy the Command line that contains all the necessary parameters. We are not going to execute the package from here. Click Close. Refer screenshots #24 - #26.
Next, we need to set up a job to run the SSIS package. We cannot choose SQL Server Integration Services Package type because that will run under 64-bit and won’t find the Excel connection provider. So, we have to run it as Operating System (CmdExec) job type. Go to SQL Server Management Studio and connect to the Database Engine. Expand SQL Server Agent and right-click on Jobs node. Select New Job…. On the General section of the Job Properties window, provide the job name as 01_SSIS_Export_To_Excel, Owner will be the user creating the job. I have a Category named SSIS, so I will select that but the default category is [Uncategorized (Local)] and provide a brief description. On the Steps section, click New… button. This will bring Job Step properties. On the General section of the Job Step properties, provide Step name as Export to Excel, Select type Operating system (CmdExec), leave the default Run as account as SQL Server Agent Service Account and provide the following Command. Click OK. On the New Job window, Click OK. Refer screenshots #27 - #31.
C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe /FILE
"D:\SSIS\Practice\20110723_1015_SO_21448_Excel_64_bit_Error.dtsx"
/CONNECTION Excel;"\"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:\SSIS\Practice\Currencies.xls;Extended Properties=""EXCEL 8.0;HDR=YES"";\""
/MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EWCDI
The new job should appear under SQL Server Agent –> Jobs node. Right-click on the newly created job 01_SSIS_Export_To_Excel and select Start Job at Step…, this will commence the job execution. The job will fail as expected because that is the context of this issue. Click Close to close the Start Jobs dialog. Refer screenshots #32 and #33.
Let’s take a look at what happened. Go to SQL Server Agent and Jobs node. Right-click on the job 01_SSIS_Export_To_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job failed. Expand the node near the red cross and click on the line that Step ID value of 1. At the bottom section, you can see the error message Option “8.0;HDR=YES’;” is not valid. Click Close to close the Log File Viewer window. Refer screenshots #34 and #35.
Now, right-click on the job and select Properties to open the Job Properties. You can also double-click on the job to bring the Job Properties window. Click on the Steps on the left section. and click Edit. Replace the command with the following command and click OK. Click OK on the Job Properties to close the window. Right-click on the job 01_SSIS_Export_To_Excel and select Start Job at Step…, this will commence the job execution. The job will fail execute successfully. Click Close to close the Start Jobs dialog. Let’s take a look at the history. Right-click on the job 01_SSIS_Export_To_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job succeeded during the second run. Expand the node near the green tick cross and click on the line that Step ID value of 1. At the bottom section, you can see the message Option The step succeeded. Click Close to close the Log File Viewer window. The file D:\SSIS\Practice\Currencies.xls will be successfully populated with the data. If you execute the job successfully multiple times, the data will get appended to the file and you will find more data. As I mentioned earlier, this is not the right-way to generate the files. This example was created to demonstrate a fix for this issue. Refer screenshots #36 - #38.
Screenshot #39 shows the differences between the working and the non-working command line arguments. The one on the right is the working command line and the left one is incorrect. It required another double quotes with backslash escape sequence to fix the error. There could be other ways to fix this well but this option seems to work.
Thus, the example demonstrated a way to fix the command line argument issue while accessing Excel data source from an SSIS package that is deployed on a 64-bit server.
Hope that helps someone.
Screenshots:
#1: Solution_Explorer
#2: New_Connection_Data_Source
#3: Select_Data_Source
#4: New_Connection
#5: Add_SSIS_Connection_Manager
#6: Excel_Connection_Manager
#7: Connection_Managers
#8: Variables
#9: Stored_Procedure_Output
#10: Control_Flow
#11: OLE_DB_Source_Connections_Manager
#12: OLE_DB_Source_Columns
#13: Excel_Destination_Editor_New
#14: Excel_Destination_Create_Table
#15: Excel_Destination_Edito
#16: Excel_Destination_Mappings
#17: Data_Flow
#18: Successful_Package_Execution_Control
#19: Successful_Package_Execution_Data_Flow
#20: C_Temp_File_Created
#21: Data_Populated
#22: File_On_Server
#23: SQL_Server_Version
#24: Execute_Package_Utility_General
#25: Execute_Package_Utility_Connection_Managers
#26: Execute_Package_Utility_Command_Line
#27: Job_New_Job
#28: New_Job_General
#29: New_Job_Step
#30: New_Job_Step_General
#31: New_Job_Steps_Added
#32: Job_Start_Job_at_Step
#33: SQL_Job_Execution_Failure
#34: View_History
#35: SQL_Job_Error_Message
#36: SQL_Job_Execution_Success
#37: SQL_Job_Success_Message
#38: Excel_File_Generated
#39: Command_Comparison
A: You can use an Excel connection in 64bit environment.
Go to the package configuration properties.
Debugging -> Debugging Options -> Run64BtRuntime -> change to False
In addition if you use SQL Agent go to the job step properties and then check the 32 bit runtime.
note: this only applies to debugging within Visual Studio...
A: Unless it's a business requirement, I suggest you move the connection string from the command line to the package and use a package configuration to define the path to the Excel file (in order not to hard-code it). This will make it easier to maintain.
*
*Define a variable @ExcelPath.
*Use connection's Expression property to construct a connection string - an example: "Data Source=" + @[User::FilePath] + ";Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBASE IV;"
*Assign a value to @ExcelPath in the package configuration.
Take a closer look at the connection string above. It's taken from a working package. I'm not sure about this, but maybe you don't need any quotes at all (the ones above are only there because the expression editor requires them).
I have also had some problems with SSIS on 64-bit SQL Server 2005. That post from my blog does not answer your question, but it is somewhat related so I am posting the link.
A: There is no 64-bit Jet OLEDB provider, so you can't access Excel files from 64-bit SSIS.
However, you can use 32-bit SSIS even on 64-bit server. It is already installed when you installed 64-bit version, and all you need to do is run the 32-bit DTEXEC.EXE - the one installed Program Files (x86)\Microsoft Sql Server\90\Dts\Binn (replace 90 with 100 if you are using SSIS 2008).
A: I kinda did what Dr Zim did but I copied the DTExec file C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe to C:\Program Files\Microsoft SQL Server\90\DTS\Binn\ folder but named the 32 bit one to DTExec32.exe
then I was able to run my SSIS script through a stored proc:
set @params = '/set \package.variables[ImportFilename].Value;"\"' + @FileName + '\"" '
set @cmd = 'dtexec32 /SQ "' + @packagename + ' ' + @params + '"'
--DECLARE @returncode int
exec master..xp_cmdshell @cmd
--exec @returncode = master..xp_cmdshell @cmd
--select @returncode
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Types of endianness What is the difference between the following types of endianness?
*
*byte (8b) invariant big and little endianness
*half-word (16b) invariant big and little endianness
*word (32b) invariant big and little endianness
*double-word (64b) invariant big and little endianness
Are there other types/variations?
A: There's also middle or mixed endian. See wikipedia for details.
The only time I had to worry about this was when writing some networking code in C. Networking typically uses big-endian IIRC. Most languages either abstract the whole thing or offer libraries to guarantee that you're using the right endian-ness though.
A: Philibert said,
bits were actually inverted
I doubt any architecture would break byte value invariance. The order of bit-fields may need inversion when mapping structs containing them against data. Such direct mapping relies on compiler specifics which are outside the C99 standard but which may still be common. Direct mapping is faster but does not comply with the C99 standard that does not stipulate packing, alignment and byte order. C99-compliant code should use slow mapping based on values rather than addresses. That is, instead of doing this,
#if LITTLE_ENDIAN
struct breakdown_t {
int least_significant_bit: 1;
int middle_bits: 10;
int most_significant_bits: 21;
};
#elif BIG_ENDIAN
struct breakdown_t {
int most_significant_bits: 21;
int middle_bits: 10;
int least_significant_bit: 1;
};
#else
#error Huh
#endif
uint32_t data = ...;
struct breakdown_t *b = (struct breakdown_t *)&data;
one should write this (and this is how the compiler would generate code anyways even for the above "direct mapping"),
uint32_t data = ...;
uint32_t least_significant_bit = data & 0x00000001;
uint32_t middle_bits = (data >> 1) & 0x000003FF;
uint32_t most_significant_bits = (data >> 11) & 0x001fffff;
The reason behind the need to invert the order of bit-fields in each endian-neutral, application-specific data storage unit is that compilers pack bit-fields into bytes of growing addresses.
The "order of bits" in each byte does not matter as the only way to extract them is by applying masks of values and by shifting to the the least-significant-bit or most-significant-bit direction. The "order of bits" issue would only become important in imaginary architectures with the notion of bit addresses. I believe all existing architectures hide this notion in hardware and provide only least vs. most significant bit extraction which is the notion based on the endian-neutral byte values.
A: There are two approaches to endian mapping: address invariance and data invariance.
Address Invariance
In this type of mapping, the address of bytes is always preserved between big and little. This has the side effect of reversing the order of significance (most significant to least significant) of a particular datum (e.g. 2 or 4 byte word) and therefore the interpretation of data. Specifically, in little-endian, the interpretation of data is least-significant to most-significant bytes whilst in big-endian, the interpretation is most-significant to least-significant. In both cases, the set of bytes accessed remains the same.
Example
Address invariance (also known as byte invariance): the byte address is constant but byte significance is reversed.
Addr Memory
7 0
| | (LE) (BE)
|----|
+0 | aa | lsb msb
|----|
+1 | bb | : :
|----|
+2 | cc | : :
|----|
+3 | dd | msb lsb
|----|
| |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xaa (preserved)
Read 2 bytes: 0xbbaa 0xaabb
Read 4 bytes: 0xddccbbaa 0xaabbccdd
Data Invariance
In this type of mapping, the relative byte significance is preserved for datum of a particular size. There are therefore different types of data invariant endian mappings for different datum sizes. For example, a 32-bit word invariant endian mapping would be used for a datum size of 32. The effect of preserving the value of particular sized datum, is that the byte addresses of bytes within the datum are reversed between big and little endian mappings.
Example
32-bit data invariance (also known as word invariance): The datum is a 32-bit word which always has the value 0xddccbbaa, independent of endianness. However, for accesses smaller than a word, the address of the bytes are reversed between big and little endian mappings.
Addr Memory
| +3 +2 +1 +0 | <- LE
|-------------------|
+0 msb | dd | cc | bb | aa | lsb
|-------------------|
+4 msb | 99 | 88 | 77 | 66 | lsb
|-------------------|
BE -> | +0 +1 +2 +3 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xdd
Read 2 bytes: 0xbbaa 0xddcc
Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
Example
16-bit data invariance (also known as half-word invariance): The datum is a 16-bit
which always has the value 0xbbaa, independent of endianness. However, for accesses smaller than a half-word, the address of the bytes are reversed between big and little endian mappings.
Addr Memory
| +1 +0 | <- LE
|---------|
+0 msb | bb | aa | lsb
|---------|
+2 msb | dd | cc | lsb
|---------|
+4 msb | 77 | 66 | lsb
|---------|
+6 msb | 99 | 88 | lsb
|---------|
BE -> | +0 +1 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xbb
Read 2 bytes: 0xbbaa 0xbbaa (preserved)
Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
Example
64-bit data invariance (also known as double-word invariance): The datum is a 64-bit
word which always has the value 0x99887766ddccbbaa, independent of endianness. However, for accesses smaller than a double-word, the address of the bytes are reversed between big and little endian mappings.
Addr Memory
| +7 +6 +5 +4 +3 +2 +1 +0 | <- LE
|---------------------------------------|
+0 msb | 99 | 88 | 77 | 66 | dd | cc | bb | aa | lsb
|---------------------------------------|
BE -> | +0 +1 +2 +3 +4 +5 +6 +7 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0x99
Read 2 bytes: 0xbbaa 0x9988
Read 4 bytes: 0xddccbbaa 0x99887766
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
A: Best article I read about endianness "Understanding Big and Little Endian Byte Order".
A: Actually, I'd describe the endianness of a machine as the order of bytes inside of a word, and not the order of bits.
By "bytes" up there I mean the "smallest unit of memory the architecture can manage individually". So, if the smallest unit is 16 bits long (what in x86 would be called a word) then a 32 bit "word" representing the value 0xFFFF0000 could be stored like this:
FFFF 0000
or this:
0000 FFFF
in memory, depending on endianness.
So, if you have 8-bit endianness, it means that every word consisting of 16 bits, will be stored as:
FF 00
or:
00 FF
and so on.
A: Practically speaking, endianess refers to the way the processor will interpret the content of a given memory location. For example, if we have memory location 0x100 with the following content (hex bytes)
0x100: 12 34 56 78 90 ab cd ef
Reads Little Endian Big Endian
8-bit: 12 12
16-bit: 34 12 12 34
32-bit: 78 56 34 12 12 34 56 78
64-bit: ef cd ab 90 78 56 34 12 12 34 56 78 90 ab cd ef
The two situations where you need to mind endianess are with networking code and if you do down casting with pointers.
TCP/IP specifies that data on the wire should be big endian. If you transmit types other than byte arrays (like pointers to structures), you should make sure to use the ntoh/hton macros to ensure the data is sent big endian. If you send from a little-endian processor to a big-endian processor (or vice versa), the data will be garbled...
Casting issues:
uint32_t* lptr = 0x100;
uint16_t data;
*lptr = 0x0000FFFF
data = *((uint16_t*)lptr);
What will be the value of data?
On a big-endian system, it would be 0 On a little-endian system, it would be FFFF
A: 13 years ago I worked on a tool portable to both a DEC ALPHA system and a PC. On this DEC ALPHA the bits were actually inverted. That is:
1010 0011
actually translated to
1100 0101
It was almost transparent and seamless in the C code except that I had a bitfield declared like
typedef struct {
int firstbit:1;
int middlebits:10;
int lastbits:21;
};
that needed to be translated to (using #ifdef conditional compiling)
typedef struct {
int lastbits:21;
int middlebits:10;
int firstbit:1;
};
A: As @erik-van-brakel answered on this post, be careful when communicating with certain PLC : Mixed-endian still alive !
Indeed, I need to communicate with a PLC (from a well known manufacturer) with (Modbus-TCP) OPC protocol and it seems that it returns me a mixed-endian on every half word. So it is still used by some of the larger manufacturers.
Here is an example with the "pieces" string :
A: the basic concept is the ordering of bits:
1010 0011
in little-endian is the same as
0011 1010
in big-endian (and vice-versa).
You'll notice the order changes by grouping, not by individual bit. I don't know of a system, for example, where
1100 0101
would be the "other-endian" version of the first version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Specifying a mySQL ENUM in a Django model How do I go about specifying and using an ENUM in a Django model?
A: If you really want to use your databases ENUM type:
*
*Use Django 1.x
*Recognize your application will only work on some databases.
*Puzzle through this documentation page:http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields
Good luck!
A: Django 3.0 has built-in support for Enums
From the documentation:
from django.utils.translation import gettext_lazy as _
class Student(models.Model):
class YearInSchool(models.TextChoices):
FRESHMAN = 'FR', _('Freshman')
SOPHOMORE = 'SO', _('Sophomore')
JUNIOR = 'JR', _('Junior')
SENIOR = 'SR', _('Senior')
GRADUATE = 'GR', _('Graduate')
year_in_school = models.CharField(
max_length=2,
choices=YearInSchool.choices,
default=YearInSchool.FRESHMAN,
)
Now, be aware that it does not enforce the choices at a database level this is Python only construct. If you want to also enforce those value at the database you could combine that with database constraints:
class Student(models.Model):
...
class Meta:
constraints = [
CheckConstraint(
check=Q(year_in_school__in=YearInSchool.values),
name="valid_year_in_school")
]
A: from django.db import models
class EnumField(models.Field):
"""
A field class that maps to MySQL's ENUM type.
Usage:
class Card(models.Model):
suit = EnumField(values=('Clubs', 'Diamonds', 'Spades', 'Hearts'))
c = Card()
c.suit = 'Clubs'
c.save()
"""
def __init__(self, *args, **kwargs):
self.values = kwargs.pop('values')
kwargs['choices'] = [(v, v) for v in self.values]
kwargs['default'] = self.values[0]
super(EnumField, self).__init__(*args, **kwargs)
def db_type(self):
return "enum({0})".format( ','.join("'%s'" % v for v in self.values) )
A: Using the choices parameter won't use the ENUM db type; it will just create a VARCHAR or INTEGER, depending on whether you use choices with a CharField or IntegerField. Generally, this is just fine. If it's important to you that the ENUM type is used at the database level, you have three options:
*
*Use "./manage.py sql appname" to see the SQL Django generates, manually modify it to use the ENUM type, and run it yourself. If you create the table manually first, "./manage.py syncdb" won't mess with it.
*If you don't want to do this manually every time you generate your DB, put some custom SQL in appname/sql/modelname.sql to perform the appropriate ALTER TABLE command.
*Create a custom field type and define the db_type method appropriately.
With any of these options, it would be your responsibility to deal with the implications for cross-database portability. In option 2, you could use database-backend-specific custom SQL to ensure your ALTER TABLE is only run on MySQL. In option 3, your db_type method would need to check the database engine and set the db column type to a type that actually exists in that database.
UPDATE: Since the migrations framework was added in Django 1.7, options 1 and 2 above are entirely obsolete. Option 3 was always the best option anyway. The new version of options 1/2 would involve a complex custom migration using SeparateDatabaseAndState -- but really you want option 3.
A: There're currently two github projects based on adding these, though I've not looked into exactly how they're implemented:
*
*Django-EnumField:
Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation.
*Django-EnumFields:
This package lets you use real Python (PEP435-style) enums with Django.
I don't think either use DB enum types, but they are in the works for first one.
A: From the Django documentation:
MAYBECHOICE = (
('y', 'Yes'),
('n', 'No'),
('u', 'Unknown'),
)
And you define a charfield in your model :
married = models.CharField(max_length=1, choices=MAYBECHOICE)
You can do the same with integer fields if you don't like to have letters
in your db.
In that case, rewrite your choices:
MAYBECHOICE = (
(0, 'Yes'),
(1, 'No'),
(2, 'Unknown'),
)
A: Setting choices on the field will allow some validation on the Django end, but it won't define any form of an enumerated type on the database end.
As others have mentioned, the solution is to specify db_type on a custom field.
If you're using a SQL backend (e.g. MySQL), you can do this like so:
from django.db import models
class EnumField(models.Field):
def __init__(self, *args, **kwargs):
super(EnumField, self).__init__(*args, **kwargs)
assert self.choices, "Need choices for enumeration"
def db_type(self, connection):
if not all(isinstance(col, basestring) for col, _ in self.choices):
raise ValueError("MySQL ENUM values should be strings")
return "ENUM({})".format(','.join("'{}'".format(col)
for col, _ in self.choices))
class IceCreamFlavor(EnumField, models.CharField):
def __init__(self, *args, **kwargs):
flavors = [('chocolate', 'Chocolate'),
('vanilla', 'Vanilla'),
]
super(IceCreamFlavor, self).__init__(*args, choices=flavors, **kwargs)
class IceCream(models.Model):
price = models.DecimalField(max_digits=4, decimal_places=2)
flavor = IceCreamFlavor(max_length=20)
Run syncdb, and inspect your table to see that the ENUM was created properly.
mysql> SHOW COLUMNS IN icecream;
+--------+-----------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| price | decimal(4,2) | NO | | NULL | |
| flavor | enum('chocolate','vanilla') | NO | | NULL | |
+--------+-----------------------------+------+-----+---------+----------------+
A: http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/
class Entry(models.Model):
LIVE_STATUS = 1
DRAFT_STATUS = 2
HIDDEN_STATUS = 3
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(DRAFT_STATUS, 'Draft'),
(HIDDEN_STATUS, 'Hidden'),
)
# ...some other fields here...
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)
live_entries = Entry.objects.filter(status=Entry.LIVE_STATUS)
draft_entries = Entry.objects.filter(status=Entry.DRAFT_STATUS)
if entry_object.status == Entry.LIVE_STATUS:
This is another nice and easy way of implementing enums although it doesn't really save enums in the database.
However it does allow you to reference the 'label' whenever querying or specifying defaults as opposed to the top-rated answer where you have to use the 'value' (which may be a number).
A: If you have to have enum type in MySQL table and not a "fake" enum (only visible on python side) then you can try Django-MySQL extension and its EnumField.
The models:
from django.db import models
from django_mysql.models import EnumField
class IceCreamFlavor(models.TextChoices):
CHOCOLATE = "chocolate"
VANILLA = "vanilla"
class IceCream(models.Model):
price = models.DecimalField(max_digits=4, decimal_places=2)
ice_cream_flavor = EnumField(choices=IceCreamFlavor.choices)
Resulting table:
mysql> SHOW COLUMNS IN myapp.db_icecream;
+------------------+-----------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+-----------------------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| price | decimal(4,2) | NO | | NULL | |
| ice_cream_flavor | enum('chocolate','vanilla') | NO | | NULL | |
+------------------+-----------------------------+------+-----+---------+----------------+
A: A the top of your models.py file, add this line after you do your imports:
enum = lambda *l: [(s,_(s)) for s in l]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "100"
} |
Q: Does Hostmonster support Django I know Hostmonster allows Python. Has anyone successfully run Django on there? Any problems?
A: http://www.hostmonsterforum.com/showpost.php?p=20003&postcount=7
I tried the archive the user posted there, and it worked like a charm.
A: I know this is an old question, but here is the answer: yes, Hostmonster does support Django
There used to be this Hostmonster KB article for details, including instructions on how to set it up, but that link appears to be dead these days, and the only article about Hostmonster article about Django is about troubleshooting. You can find instructions on how to set up Django on Hostmonster elsewhere.
A: Well, if it support Python, you might be able to run Django using a FastCGI setup, as described here: FastCGI Docs. If it supports mod_python (which I guess it's what you mean), then sure, you can install it using the steps listed here: ModPython docs
A: Hostmonster uses cPanel (possible with CentOS), just like other host providers. If you research into cPanel , you are more likely to get your answer.
Generally, the answer is "no" since out-of-the-box cPanel does not support python 2.5 or mod_wsgi. But it does support Apache2, so it's possible that hostmonster could use mod_wsgi to run sites built with Django.
A: There is a Github repository for hostmonster and Django it helps me:
hostmonster-django.markdown
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What Predefined #if symbos does c# have? #if SYMBOL
//code
#endif
what values does C# predefine for use?
A: Depends on what /define compiler options you use. Visual Studio puts the DEBUG symbol in there for you via the project settings, but you could create any ones that you want.
A: To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from #define and /define.
#if on MSDN
A: Well, that depends on the compiler you are using, and the command line options. Mono defines different names than Microsoft's compiler by default, and depending on what system you are you get different defines, etc.
If you provide a more specific system for which you are compiling, we might be able to come up with the list for that particular system (for example: x64 Vista system, using Visual Studio 2008).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Recommended iPhone Development Resources This is my first post here and I wanted to get some input from people doing iPhone development. Other than the Apple DevCenter, where are there good sites to learn iPhone developement?
I know Apple has a tough NDA but there has to be people talking about writing applications for the iPhone.
A: Pretty impressed with http://www.appsamuck.com/
A new iPhone app is written everyday, and listed on the site with source code and screen shots.
A: this is probably a good place to start
http://developer.apple.com/iphone/
A: This site covers some of the basics with little regard for the NDA. Start at the bottom and work up.
A: Craig Hockenberry (developer of Twitterrific) blogs about iPhone development issues at furbo.org
A: Apple now has developer forums, accessible to registered developers: https://devforums.apple.com
A: My friend suggested me this site edumobile which provides you with detailed information on iPhone development it is significantly a useful resource hope this will help you.
A: In http://www.raywenderlich.com/tutorials you will find a lots of good tutorials, and you will be up to date with new iOS features as soon as Apple release then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Grouping runs of data SQL Experts,
Is there an efficient way to group runs of data together using SQL?
Or is it going to be more efficient to process the data in code.
For example if I have the following data:
ID|Name
01|Harry Johns
02|Adam Taylor
03|John Smith
04|John Smith
05|Bill Manning
06|John Smith
I need to display this:
Harry Johns
Adam Taylor
John Smith (2)
Bill Manning
John Smith
@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.
A: Try this:
select n.name,
(select count(*)
from myTable n1
where n1.name = n.name and n1.id >= n.id and (n1.id <=
(
select isnull(min(nn.id), (select max(id) + 1 from myTable))
from myTable nn
where nn.id > n.id and nn.name <> n.name
)
))
from myTable n
where not exists (
select 1
from myTable n3
where n3.name = n.name and n3.id < n.id and n3.id > (
select isnull(max(n4.id), (select min(id) - 1 from myTable))
from myTable n4
where n4.id < n.id and n4.name <> n.name
)
)
I think that'll do what you want. Bit of a kludge though.
Phew! After a few edits I think I have all the edge cases sorted out.
A: I hate cursors with a passion... but here's a dodgy cursor version...
Declare @NewName Varchar(50)
Declare @OldName Varchar(50)
Declare @CountNum int
Set @CountNum = 0
DECLARE nameCursor CURSOR FOR
SELECT Name
FROM NameTest
OPEN nameCursor
FETCH NEXT FROM nameCursor INTO @NewName
WHILE @@FETCH_STATUS = 0
BEGIN
if @OldName <> @NewName
BEGIN
Print @OldName + ' (' + Cast(@CountNum as Varchar(50)) + ')'
Set @CountNum = 0
END
SELECT @OldName = @NewName
FETCH NEXT FROM nameCursor INTO @NewName
Set @CountNum = @CountNum + 1
END
Print @OldName + ' (' + Cast(@CountNum as Varchar(50)) + ')'
CLOSE nameCursor
DEALLOCATE nameCursor
A: My solution just for kicks (this was a fun exercise), no cursors, no iterations, but i do have a helper field
-- Setup test table
DECLARE @names TABLE (
id INT IDENTITY(1,1),
name NVARCHAR(25) NOT NULL,
grp UNIQUEIDENTIFIER NULL
)
INSERT @names (name)
SELECT 'Harry Johns' UNION ALL
SELECT 'Adam Taylor' UNION ALL
SELECT 'John Smith' UNION ALL
SELECT 'John Smith' UNION ALL
SELECT 'Bill Manning' UNION ALL
SELECT 'Bill Manning' UNION ALL
SELECT 'Bill Manning' UNION ALL
SELECT 'John Smith' UNION ALL
SELECT 'Bill Manning'
-- Set the first id's group to a newid()
UPDATE n
SET grp = newid()
FROM @names n
WHERE n.id = (SELECT MIN(id) FROM @names)
-- Set the group to a newid() if the name does not equal the previous
UPDATE n
SET grp = newid()
FROM @names n
INNER JOIN @names b
ON (n.ID - 1) = b.ID
AND ISNULL(b.Name, '') <> n.Name
-- Set groups that are null to the previous group
-- Keep on doing this until all groups have been set
WHILE (EXISTS(SELECT 1 FROM @names WHERE grp IS NULL))
BEGIN
UPDATE n
SET grp = b.grp
FROM @names n
INNER JOIN @names b
ON (n.ID - 1) = b.ID
AND n.grp IS NULL
END
-- Final output
SELECT MIN(id) AS id_start,
MAX(id) AS id_end,
name,
count(1) AS consecutive
FROM @names
GROUP BY grp,
name
ORDER BY id_start
/*
Results:
id_start id_end name consecutive
1 1 Harry Johns 1
2 2 Adam Taylor 1
3 4 John Smith 2
5 7 Bill Manning 3
8 8 John Smith 1
9 9 Bill Manning 1
*/
A: Well, this:
select Name, count(Id)
from MyTable
group by Name
will give you this:
Harry Johns, 1
Adam Taylor, 1
John Smith, 2
Bill Manning, 1
and this (MS SQL syntax):
select Name +
case when ( count(Id) > 1 )
then ' ('+cast(count(Id) as varchar)+')'
else ''
end
from MyTable
group by Name
will give you this:
Harry Johns
Adam Taylor
John Smith (2)
Bill Manning
Did you actually want that other John Smith on the end of your results?
EDIT: Oh I see, you want consecutive runs grouped. In that case, I'd say you need a cursor or to do it in your program code.
A: How about this:
declare @tmp table (Id int, Nm varchar(50));
insert @tmp select 1, 'Harry Johns';
insert @tmp select 2, 'Adam Taylor';
insert @tmp select 3, 'John Smith';
insert @tmp select 4, 'John Smith';
insert @tmp select 5, 'Bill Manning';
insert @tmp select 6, 'John Smith';
select * from @tmp order by Id;
select Nm, count(1) from
(
select Id, Nm,
case when exists (
select 1 from @tmp t2
where t2.Nm=t1.Nm
and (t2.Id = t1.Id + 1 or t2.Id = t1.Id - 1))
then 1 else 0 end as Run
from @tmp t1
) truns group by Nm, Run
[Edit] That can be shortened a bit
select Nm, count(1) from (select Id, Nm, case when exists (
select 1 from @tmp t2 where t2.Nm=t1.Nm
and abs(t2.Id-t1.Id)=1) then 1 else 0 end as Run
from @tmp t1) t group by Nm, Run
A: For this particular case, all you need to do is group by the name and ask for the count, like this:
select Name, count(*)
from MyTable
group by Name
That'll get you the count for each name as a second column.
You can get it all as one column by concatenating like this:
select Name + ' (' + cast(count(*) as varchar) + ')'
from MyTable
group by Name
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Enumerate Windows user group members on remote system using c# Within c#, I need to be able to
*
*Connect to a remote system, specifying username/password as appropriate
*List the members of a localgroup on that system
*Fetch the results back to the executing computer
So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administrators including SOMESYSTEM\Administrator, SOMESYSTEM\Bob, DOMAIN\AlanH, "DOMAIN\Domain Administrators".
I've tried this with system.directoryservices.accountmanagement but am running into problems with authentication. Sometimes I get:
Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. (Exception from HRESULT: 0x800704C3)
The above is trying because there will be situations where I simply cannot unmap existing drives or UNC connections.
Other times my program gets UNKNOWN ERROR and the security log on the remote system reports an error 675, code 0x19 which is KDC_ERR_PREAUTH_REQUIRED.
I need a simpler and less error prone way to do this!
A: davidg was on the right track, and I am crediting him with the answer.
But the WMI query necessary was a little less than straightfoward, since I needed not just a list of users for the whole machine, but the subset of users and groups, whether local or domain, that were members of the local Administrators group. For the record, that WMI query was:
SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = "Win32_Group.Domain='thehostname',Name='thegroupname'"
Here's the full code snippet:
public string GroupMembers(string targethost, string groupname, string targetusername, string targetpassword)
{
StringBuilder result = new StringBuilder();
try
{
ConnectionOptions Conn = new ConnectionOptions();
if (targethost != Environment.MachineName) //WMI errors if creds given for localhost
{
Conn.Username = targetusername; //can be null
Conn.Password = targetpassword; //can be null
}
Conn.Timeout = TimeSpan.FromSeconds(2);
ManagementScope scope = new ManagementScope("\\\\" + targethost + "\\root\\cimv2", Conn);
scope.Connect();
StringBuilder qs = new StringBuilder();
qs.Append("SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \"Win32_Group.Domain='");
qs.Append(targethost);
qs.Append("',Name='");
qs.Append(groupname);
qs.AppendLine("'\"");
ObjectQuery query = new ObjectQuery(qs.ToString());
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
ManagementPath path = new ManagementPath(m["PartComponent"].ToString());
{
String[] names = path.RelativePath.Split(',');
result.Append(names[0].Substring(names[0].IndexOf("=") + 1).Replace("\"", " ").Trim() + "\\");
result.AppendLine(names[1].Substring(names[1].IndexOf("=") + 1).Replace("\"", " ").Trim());
}
}
return result.ToString();
}
catch (Exception e)
{
Console.WriteLine("Error. Message: " + e.Message);
return "fail";
}
}
So, if I invoke Groupmembers("Server1", "Administrators", "myusername", "mypassword"); I get a single string returned with:
SERVER1\Administrator
MYDOMAIN\Domain Admins
The actual WMI return is more like this:
\\SERVER1\root\cimv2:Win32_UserAccount.Domain="SERVER1",Name="Administrator"
... so as you can see, I had to do a little string manipulation to pretty it up.
A: This should be easy to do using WMI. Here you have a pointer to some docs:
WMI Documentation for Win32_UserAccount
Even if you have no previous experience with WMI, it should be quite easy to turn that VB Script code at the bottom of the page into some .NET code.
Hope this helped!
A: I would recommend using the Win32 API function NetLocalGroupGetMembers. It is much more straight forward than trying to figure out the crazy LDAP syntax, which is necessary for some of the other solutions recommended here. As long as you impersonate the user you want to run the check as by calling "LoginUser", you should not run into any security issues.
You can find sample code for doing the impersonation here.
If you need help figuring out how to call "NetLocalGroupGetMembers" from C#, I reccomend that you checkout Jared Parson's PInvoke assistant, which you can download from codeplex.
If you are running the code in an ASP.NET app running in IIS, and want to impersonate the user accessing the website in order to make the call, then you may need to grant "Trusted for Delegation" permission to the production web server.
If you are running on the desktop, then using the active user's security credentials should not be a problem.
It is possible that you network admin could have revoked access to the "Securable Object" for the particular machine you are trying to access. Unfortunately that access is necessary for all of the network management api functions to work. If that is the case, then you will need to grant access to the "Securable Object" for whatever users you want to execute as. With the default windows security settings all authenticated users should have access, however.
I hope this helps.
-Scott
A: You should be able to do this with System.DirectoryServices.DirectoryEntry. If you are having trouble running it remotely, maybe you could install something on the remote machines to give you your data via some sort of RPC, like remoting or a web service. But I think what you're trying should be possible remotely without getting too fancy.
A: If Windows won't let you connect through it's login mechanism, I think your only option is to run something on the remote machine with an open port (either directly or through remoting or a web service, as mentioned).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: In SQL Server, how do I generate a CREATE TABLE statement for a given table? I've spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I'm posting it here, since I think it might be useful to others.
If anyone has a better script, or anything to add, please post it.
Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.
A: If the application you are generating the scripts from is a .NET application, you may want to look into using SMO (Sql Management Objects). Reference this SQL Team link on how to use SMO to script objects.
A: One more variant with foreign keys support and in one statement:
SELECT
obj.name
,'CREATE TABLE [' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')'
+ ISNULL(' ' + refs.list, '')
FROM sysobjects obj
CROSS APPLY (
SELECT
CHAR(10)
+ ' [' + column_name + '] '
+ data_type
+ CASE data_type
WHEN 'sql_variant' THEN ''
WHEN 'text' THEN ''
WHEN 'ntext' THEN ''
WHEN 'xml' THEN ''
WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'
ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')
END
+ ' '
+ case when exists ( -- Identity skip
select id from syscolumns
where object_name(id) = obj.name
and name = column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(obj.name) as varchar) + ',' +
cast(ident_incr(obj.name) as varchar) + ')'
else ''
end + ' '
+ CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END
+ 'NULL'
+ CASE WHEN information_schema.columns.column_default IS NOT NULL THEN ' DEFAULT ' + information_schema.columns.column_default ELSE '' END
+ ','
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE table_name = obj.name
ORDER BY ordinal_position
FOR XML PATH('')
) cols (list)
CROSS APPLY(
SELECT
CHAR(10) + 'ALTER TABLE ' + obj.name + '_noident_temp ADD ' + LEFT(alt, LEN(alt)-1)
FROM(
SELECT
CHAR(10)
+ ' CONSTRAINT ' + tc.constraint_name
+ ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'
+ COALESCE(CHAR(10) + r.list, ', ')
FROM
information_schema.table_constraints tc
CROSS APPLY(
SELECT
'[' + kcu.column_name + '], '
FROM
information_schema.key_column_usage kcu
WHERE
kcu.constraint_name = tc.constraint_name
ORDER BY
kcu.ordinal_position
FOR XML PATH('')
) c (list)
OUTER APPLY(
-- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
SELECT
' REFERENCES [' + kcu1.constraint_schema + '].' + '[' + kcu2.table_name + ']' + '(' + kcu2.column_name + '), '
FROM information_schema.referential_constraints as rc
JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)
JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)
WHERE
kcu1.constraint_catalog = tc.constraint_catalog AND kcu1.constraint_schema = tc.constraint_schema AND kcu1.constraint_name = tc.constraint_name
) r (list)
WHERE tc.table_name = obj.name
FOR XML PATH('')
) a (alt)
) refs (list)
WHERE
xtype = 'U'
AND name NOT IN ('dtproperties')
AND obj.name = 'your_table_name'
You could try in is sqlfiddle: http://sqlfiddle.com/#!6/e3b66/3/0
A: I modified the accepted answer and now it can get the command including primary key and foreign key in a certain schema.
declare @table varchar(100)
declare @schema varchar(100)
set @table = 'Persons' -- set table name here
set @schema = 'OT' -- set SCHEMA name here
declare @sql table(s varchar(1000), id int identity)
-- create statement
insert into @sql(s) values ('create table ' + @table + ' (')
-- column list
insert into @sql(s)
select
' '+column_name+' ' +
data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=@table
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(@table) as varchar) + ',' +
cast(ident_incr(@table) as varchar) + ')'
else ''
end + ' ' +
( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','
from information_schema.columns where table_name = @table and table_schema = @schema
order by ordinal_position
-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'
if ( @pkname is not null ) begin
insert into @sql(s) values(' PRIMARY KEY (')
insert into @sql(s)
select ' '+COLUMN_NAME+',' from information_schema.key_column_usage
where constraint_name = @pkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' )')
end
else begin
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
end
-- foreign key
declare @fkname varchar(100)
select @fkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='FOREIGN KEY'
if ( @fkname is not null ) begin
insert into @sql(s) values(',')
insert into @sql(s) values(' FOREIGN KEY (')
insert into @sql(s)
select ' '+COLUMN_NAME+',' from information_schema.key_column_usage
where constraint_name = @fkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' ) REFERENCES ')
insert into @sql(s)
SELECT
OBJECT_NAME(fk.referenced_object_id)
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
INNER JOIN
sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
where fk.name = @fkname
insert into @sql(s)
SELECT
'('+c2.name+')'
FROM
sys.foreign_keys fk
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
INNER JOIN
sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
where fk.name = @fkname
end
-- closing bracket
insert into @sql(s) values( ')' )
-- result!
select s from @sql order by id
A: I'm going to improve the answer by supporting partitioned tables:
find partition scheme and partition key using below scritps:
declare @partition_scheme varchar(100) = (
select distinct ps.Name AS PartitionScheme
from sys.indexes i
join sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id
join sys.partition_schemes ps on ps.data_space_id = i.data_space_id
where i.object_id = object_id('your table name')
)
print @partition_scheme
declare @partition_column varchar(100) = (
select c.name
from sys.tables t
join sys.indexes i
on(i.object_id = t.object_id
and i.index_id < 2)
join sys.index_columns ic
on(ic.partition_ordinal > 0
and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c
on(c.object_id = ic.object_id
and c.column_id = ic.column_id)
where t.object_id = object_id('your table name')
)
print @partition_column
then change the generation query by adding below line at the right place:
+ IIF(@partition_scheme is null, '', 'ON [' + @partition_scheme + ']([' + @partition_column + '])')
A: Credit due to @Blorgbeard for sharing his script. I'll certainly bookmark it in case I need it.
Yes, you can "right click" on the table and script the CREATE TABLE script, but:
*
*The a script will contain loads of cruft (interested in the extended properties anyone?)
*If you have 200+ tables in your schema, it's going to take you half a day to script the lot by hand.
With this script converted into a stored procedure, and combined with a wrapper script you would have a nice automated way to dump your table design into source control etc.
The rest of your DB code (SP's, FK indexes, Triggers etc) would be under source control anyway ;)
A: Something I've noticed - in the INFORMATION_SCHEMA.COLUMNS view, CHARACTER_MAXIMUM_LENGTH gives a size of 2147483647 (2^31-1) for field types such as image and text. ntext is 2^30-1 (being double-byte unicode and all).
This size is included in the output from this query, but it is invalid for these data types in a CREATE statement (they should not have a maximum size value at all). So unless the results from this are manually corrected, the CREATE script won't work given these data types.
I imagine it's possible to fix the script to account for this, but that's beyond my SQL capabilities.
A: -- or you could create a stored procedure ... first with Id creation
USE [db]
GO
/****** Object: StoredProcedure [dbo].[procUtils_InsertGeneratorWithId] Script Date: 06/13/2009 22:18:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROC [dbo].[procUtils_InsertGeneratorWithId]
(
@domain_user varchar(50),
@tableName varchar(100)
)
as
--Declare a cursor to retrieve column specific information for the specified table
DECLARE cursCol CURSOR FAST_FORWARD FOR
SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName
OPEN cursCol
DECLARE @string nvarchar(3000) --for storing the first half of INSERT statement
DECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement
DECLARE @dataType nvarchar(1000) --data types returned for respective columns
DECLARE @IDENTITY_STRING nvarchar ( 100 )
SET @IDENTITY_STRING = ' '
select @IDENTITY_STRING
SET @string='INSERT '+@tableName+'('
SET @stringData=''
DECLARE @colName nvarchar(50)
FETCH NEXT FROM cursCol INTO @colName,@dataType
IF @@fetch_status<>0
begin
print 'Table '+@tableName+' not found, processing skipped.'
close curscol
deallocate curscol
return
END
WHILE @@FETCH_STATUS=0
BEGIN
IF @dataType in ('varchar','char','nchar','nvarchar')
BEGIN
--SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+'
SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+'
END
ELSE
if @dataType in ('text','ntext') --if the datatype is text or something else
BEGIN
SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'
END
ELSE
IF @dataType = 'money' --because money doesn't get converted from varchar implicitly
BEGIN
SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'
END
ELSE
IF @dataType='datetime'
BEGIN
--SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'
--SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations
--SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'
SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'
-- 'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations
END
ELSE
IF @dataType='image'
BEGIN
SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+'
END
ELSE --presuming the data type is int,bit,numeric,decimal
BEGIN
--SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'
--SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'
SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+'
END
SET @string=@string+@colName+','
FETCH NEXT FROM cursCol INTO @colName,@dataType
END
DECLARE @Query nvarchar(4000)
SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName
exec sp_executesql @query
--select @query
CLOSE cursCol
DEALLOCATE cursCol
/*
USAGE
*/
GO
-- and second without iD INSERTION
USE [db]
GO
/****** Object: StoredProcedure [dbo].[procUtils_InsertGenerator] Script Date: 06/13/2009 22:20:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[procUtils_InsertGenerator]
(
@domain_user varchar(50),
@tableName varchar(100)
)
as
--Declare a cursor to retrieve column specific information for the specified table
DECLARE cursCol CURSOR FAST_FORWARD FOR
-- SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName
/* NEW
SELECT c.name , sc.data_type FROM sys.extended_properties AS ep
INNER JOIN sys.tables AS t ON ep.major_id = t.object_id
INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id
= c.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and
c.name = sc.column_name
WHERE t.name = @tableName and c.is_identity=0
*/
select object_name(c.object_id) "TABLE_NAME", c.name "COLUMN_NAME", s.name "DATA_TYPE"
from sys.columns c
join sys.systypes s on (s.xtype = c.system_type_id)
where object_name(c.object_id) in (select name from sys.tables where name not like 'sysdiagrams')
AND object_name(c.object_id) in (select name from sys.tables where [name]=@tableName ) and c.is_identity=0 and s.name not like 'sysname'
OPEN cursCol
DECLARE @string nvarchar(3000) --for storing the first half of INSERT statement
DECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement
DECLARE @dataType nvarchar(1000) --data types returned for respective columns
DECLARE @IDENTITY_STRING nvarchar ( 100 )
SET @IDENTITY_STRING = ' '
select @IDENTITY_STRING
SET @string='INSERT '+@tableName+'('
SET @stringData=''
DECLARE @colName nvarchar(50)
FETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType
IF @@fetch_status<>0
begin
print 'Table '+@tableName+' not found, processing skipped.'
close curscol
deallocate curscol
return
END
WHILE @@FETCH_STATUS=0
BEGIN
IF @dataType in ('varchar','char','nchar','nvarchar')
BEGIN
--SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+'
SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+'
END
ELSE
if @dataType in ('text','ntext') --if the datatype is text or something else
BEGIN
SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'
END
ELSE
IF @dataType = 'money' --because money doesn't get converted from varchar implicitly
BEGIN
SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'
END
ELSE
IF @dataType='datetime'
BEGIN
--SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'
--SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations
--SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'
SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'
-- 'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations
END
ELSE
IF @dataType='image'
BEGIN
SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+'
END
ELSE --presuming the data type is int,bit,numeric,decimal
BEGIN
--SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'
--SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'
SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+'
END
SET @string=@string+@colName+','
FETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType
END
DECLARE @Query nvarchar(4000)
SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName
exec sp_executesql @query
--select @query
CLOSE cursCol
DEALLOCATE cursCol
/*
use poc
go
DECLARE @RC int
DECLARE @domain_user varchar(50)
DECLARE @tableName varchar(100)
-- TODO: Set parameter values here.
set @domain_user='yorgeorg'
set @tableName = 'tbGui_WizardTabButtonAreas'
EXECUTE @RC = [POC].[dbo].[procUtils_InsertGenerator]
@domain_user
,@tableName
*/
GO
A: Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.
declare @schema varchar(100), @table varchar(100)
set @schema = 'dbo' -- set schema name here
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)
-- create statement
insert into @sql(s) values ('create table [' + @table + '] (')
-- column list
insert into @sql(s)
select
' ['+column_name+'] ' +
data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=@table
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(@table) as varchar) + ',' +
cast(ident_incr(@table) as varchar) + ')'
else ''
end + ' ' +
( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','
from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema
order by ordinal_position
-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = @table and constraint_type='PRIMARY KEY'
if ( @pkname is not null ) begin
insert into @sql(s) values(' PRIMARY KEY (')
insert into @sql(s)
select ' ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
where constraint_name = @pkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' )')
end
else begin
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
end
-- closing bracket
insert into @sql(s) values( ')' )
-- result!
select s from @sql order by id
A: Show create table in classic asp (handles constraints, primary keys, copying the table structure and/or data ...)
Sql server Show create table
Mysql-style "Show create table" and "show create database" commands from Microsoft sql server.
The script is written is Microsoft asp-language and is quite easy to port to another language.*
A: I include definitions for computed columns
select 'CREATE TABLE [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END, name
from sysobjects so
cross apply
(SELECT
case when comps.definition is not null then ' ['+column_name+'] AS ' + comps.definition
else
' ['+column_name+'] ' + data_type +
case
when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')
then ''
when data_type in ('float')
then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'
when data_type in ('datetime2', 'datetimeoffset', 'time')
then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'
when data_type in ('decimal', 'numeric')
then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'
when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1
then '(max)'
when character_maximum_length is not null
then '(' + cast(character_maximum_length as varchar(11)) + ')'
else ''
end + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' +
(case when information_schema.columns.IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END
end + ', '
from information_schema.columns
left join sys.computed_columns comps
on OBJECT_ID(information_schema.columns.TABLE_NAME)=comps.object_id and information_schema.columns.COLUMN_NAME=comps.name
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
A: I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use
select into x from db.schema.y where 1=0
to copy the table to a new DB
A: There is a Powershell script buried in the msdb forums that will script all the tables and related objects:
# Script all tables in a database
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
| out-null
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') '<Servername>'
$db = $s.Databases['<Database>']
$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
$scrp.Options.AppendToFile = $True
$scrp.Options.ClusteredIndexes = $True
$scrp.Options.DriAll = $True
$scrp.Options.ScriptDrops = $False
$scrp.Options.IncludeHeaders = $False
$scrp.Options.ToFileOnly = $True
$scrp.Options.Indexes = $True
$scrp.Options.WithDependencies = $True
$scrp.Options.FileName = 'C:\Temp\<Database>.SQL'
foreach($item in $db.Tables) { $tablearray+=@($item) }
$scrp.Script($tablearray)
Write-Host "Scripting complete"
A: I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply).
select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from sysobjects so
cross apply
(SELECT
' ['+column_name+'] ' +
data_type + case data_type
when 'sql_variant' then ''
when 'text' then ''
when 'ntext' then ''
when 'xml' then ''
when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' +
(case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' +
case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', '
from information_schema.columns where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
Update: Added handling of the XML data type
Update 2: Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name
A: Support for schemas:
This is an updated version that amends the great answer from David, et al. Added is support for named schemas. It should be noted this may break if there's actually tables of the same name present within various schemas. Another improvement is the use of the official QuoteName() function.
SELECT
t.TABLE_CATALOG,
t.TABLE_SCHEMA,
t.TABLE_NAME,
'create table '+QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name) + ' (' + LEFT(o.List, Len(o.List)-1) + '); '
+ CASE WHEN tc.Constraint_Name IS NULL THEN ''
ELSE
'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA)+'.' + QuoteName(so.name)
+ ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + '); '
END as 'SQL_CREATE_TABLE'
FROM sysobjects so
CROSS APPLY (
SELECT
' ['+column_name+'] '
+ data_type
+ case data_type
when 'sql_variant' then ''
when 'text' then ''
when 'ntext' then ''
when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else
coalesce(
'('+ case when character_maximum_length = -1
then 'MAX'
else cast(character_maximum_length as varchar) end
+ ')','')
end
+ ' '
+ case when exists (
SELECT id
FROM syscolumns
WHERE
object_name(id) = so.name
and name = column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end
+ ' '
+ (case when IS_NULLABLE = 'No' then 'NOT ' else '' end)
+ 'NULL '
+ case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT
ELSE ''
END
+ ',' -- can't have a field name or we'll end up with XML
FROM information_schema.columns
WHERE table_name = so.name
ORDER BY ordinal_position
FOR XML PATH('')
) o (list)
LEFT JOIN information_schema.table_constraints tc on
tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
LEFT JOIN information_schema.tables t on
t.Table_name = so.Name
CROSS APPLY (
SELECT QuoteName(Column_Name) + ', '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY ORDINAL_POSITION
FOR XML PATH('')
) j (list)
WHERE
xtype = 'U'
AND name NOT IN ('dtproperties')
-- AND so.name = 'ASPStateTempSessions'
;
..
For use in Management Studio:
One detractor to the sql code above is if you test it using SSMS, long statements aren't easy to read. So, as per this helpful post, here's another version that's somewhat modified to be easier on the eyes after clicking the link of a cell in the grid. The results are more readily identifiable as nicely formatted CREATE TABLE statements for each table in the db.
-- settings
DECLARE @CRLF NCHAR(2)
SET @CRLF = Nchar(13) + NChar(10)
DECLARE @PLACEHOLDER NCHAR(3)
SET @PLACEHOLDER = '{:}'
-- the main query
SELECT
t.TABLE_CATALOG,
t.TABLE_SCHEMA,
t.TABLE_NAME,
CAST(
REPLACE(
'create table ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.name) + ' (' + @CRLF
+ LEFT(o.List, Len(o.List) - (LEN(@PLACEHOLDER)+2)) + @CRLF + ');' + @CRLF
+ CASE WHEN tc.Constraint_Name IS NULL THEN ''
ELSE
'ALTER TABLE ' + QuoteName(t.TABLE_SCHEMA) + '.' + QuoteName(so.Name)
+ ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY (' + LEFT(j.List, Len(j.List) - 1) + ');' + @CRLF
END,
@PLACEHOLDER,
@CRLF
)
AS XML) as 'SQL_CREATE_TABLE'
FROM sysobjects so
CROSS APPLY (
SELECT
' '
+ '['+column_name+'] '
+ data_type
+ case data_type
when 'sql_variant' then ''
when 'text' then ''
when 'ntext' then ''
when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else
coalesce(
'('+ case when character_maximum_length = -1
then 'MAX'
else cast(character_maximum_length as varchar) end
+ ')','')
end
+ ' '
+ case when exists (
SELECT id
FROM syscolumns
WHERE
object_name(id) = so.name
and name = column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end
+ ' '
+ (case when IS_NULLABLE = 'No' then 'NOT ' else '' end)
+ 'NULL '
+ case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT
ELSE ''
END
+ ', '
+ @PLACEHOLDER -- note, can't have a field name or we'll end up with XML
FROM information_schema.columns where table_name = so.name
ORDER BY ordinal_position
FOR XML PATH('')
) o (list)
LEFT JOIN information_schema.table_constraints tc on
tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
LEFT JOIN information_schema.tables t on
t.Table_name = so.Name
CROSS APPLY (
SELECT QUOTENAME(Column_Name) + ', '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY ORDINAL_POSITION
FOR XML PATH('')
) j (list)
WHERE
xtype = 'U'
AND name NOT IN ('dtproperties')
-- AND so.name = 'ASPStateTempSessions'
;
Not to belabor the point, but here's the functionally equivalent example outputs for comparison:
-- 1 (scripting version)
create table [dbo].[ASPStateTempApplications] ( [AppId] int NOT NULL , [AppName] char(280) NOT NULL ); ALTER TABLE [dbo].[ASPStateTempApplications] ADD CONSTRAINT PK__ASPState__8E2CF7F908EA5793 PRIMARY KEY ([AppId]);
-- 2 (SSMS version)
create table [dbo].[ASPStateTempSessions] (
[SessionId] nvarchar(88) NOT NULL ,
[Created] datetime NOT NULL DEFAULT (getutcdate()),
[Expires] datetime NOT NULL ,
[LockDate] datetime NOT NULL ,
[LockDateLocal] datetime NOT NULL ,
[LockCookie] int NOT NULL ,
[Timeout] int NOT NULL ,
[Locked] bit NOT NULL ,
[SessionItemShort] varbinary(7000) NULL ,
[SessionItemLong] image(2147483647) NULL ,
[Flags] int NOT NULL DEFAULT ((0))
);
ALTER TABLE [dbo].[ASPStateTempSessions] ADD CONSTRAINT PK__ASPState__C9F4929003317E3D PRIMARY KEY ([SessionId]);
..
Detracting factors:
It should be noted that I remain relatively unhappy with this due to the lack of support for indeces other than a primary key. It remains suitable for use as a mechanism for simple data export or replication.
A: A query based on Hubbitus answer.
*
*includes schema names
*fixes foreign keys with more than one field
*includes CASCADE UPDATE & DELETE
*includes a conditioned DROP TABLE
SELECT
Schema_Name = SCHEMA_NAME(obj.uid)
, Table_Name = name
, Drop_Table = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + SCHEMA_NAME(obj.uid) + ''' AND TABLE_NAME = ''' + obj.name + '''))
DROP TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] '
, Create_Table ='
CREATE TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')' + ISNULL(' ' + refs.list, '')
FROM sysobjects obj
CROSS APPLY (
SELECT
CHAR(10)
+ ' [' + column_name + '] '
+ data_type
+ CASE data_type
WHEN 'sql_variant' THEN ''
WHEN 'text' THEN ''
WHEN 'ntext' THEN ''
WHEN 'xml' THEN ''
WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'
ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')
END
+ ' '
+ case when exists ( -- Identity skip
select id from syscolumns
where id = obj.id
and name = column_name
and columnproperty(id, name, 'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(obj.name) as varchar) + ',' +
cast(ident_incr(obj.name) as varchar) + ')'
else ''
end + ' '
+ CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END
+ 'NULL'
+ CASE WHEN IC.column_default IS NOT NULL THEN ' DEFAULT ' + IC.column_default ELSE '' END
+ ','
FROM INFORMATION_SCHEMA.COLUMNS IC
WHERE IC.table_name = obj.name
AND IC.TABLE_SCHEMA = SCHEMA_NAME(obj.uid)
ORDER BY ordinal_position
FOR XML PATH('')
) cols (list)
CROSS APPLY(
SELECT
CHAR(10) + 'ALTER TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] ADD ' + LEFT(alt, LEN(alt)-1)
FROM(
SELECT
CHAR(10)
+ ' CONSTRAINT ' + tc.constraint_name
+ ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'
+ COALESCE(CHAR(10) + r.list, ', ')
FROM information_schema.table_constraints tc
CROSS APPLY(
SELECT '[' + kcu.column_name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.constraint_name = tc.constraint_name
ORDER BY kcu.ordinal_position
FOR XML PATH('')
) c (list)
OUTER APPLY(
-- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
SELECT LEFT(f.list, LEN(f.list)-1) + ')' + IIF(rc.DELETE_RULE = 'NO ACTION', '', ' ON DELETE ' + rc.DELETE_RULE) + IIF(rc.UPDATE_RULE = 'NO ACTION', '', ' ON UPDATE ' + rc.UPDATE_RULE) + ', '
FROM information_schema.referential_constraints rc
CROSS APPLY(
SELECT IIF(kcu.ordinal_position = 1, ' REFERENCES [' + kcu.table_schema + '].[' + kcu.table_name + '] (', '')
+ '[' + kcu.column_name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.constraint_catalog = rc.unique_constraint_catalog AND kcu.constraint_schema = rc.unique_constraint_schema AND kcu.constraint_name = rc.unique_constraint_name
ORDER BY kcu.ordinal_position
FOR XML PATH('')
) f (list)
WHERE rc.constraint_catalog = tc.constraint_catalog
AND rc.constraint_schema = tc.constraint_schema
AND rc.constraint_name = tc.constraint_name
) r (list)
WHERE tc.table_name = obj.name
FOR XML PATH('')
) a (alt)
) refs (list)
WHERE xtype = 'U'
To combine drop table (if exists) with create use like this:
SELECT Drop_Table + CHAR(10) + Create_Table FROM SysCreateTables
A: If you are using management studio and have the query analyzer window open you can drag the table name to the query analyzer window and ... bingo! you get the table script.
I've not tried this in SQL2008
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "83"
} |
Q: In C++, what is a virtual base class? I want to know what a "virtual base class" is and what it means.
Let me show an example:
class Foo
{
public:
void DoSomething() { /* ... */ }
};
class Bar : public virtual Foo
{
public:
void DoSpecific() { /* ... */ }
};
A: I'd like to add to OJ's kind clarifications.
Virtual inheritance doesn't come without a price. Like with all things virtual, you get a performance hit. There is a way around this performance hit that is possibly less elegant.
Instead of breaking the diamond by deriving virtually, you can add another layer to the diamond, to get something like this:
B
/ \
D11 D12
| |
D21 D22
\ /
DD
None of the classes inherit virtually, all inherit publicly. Classes D21 and D22 will then hide virtual function f() which is ambiguous for DD, perhaps by declaring the function private. They'd each define a wrapper function, f1() and f2() respectively, each calling class-local (private) f(), thus resolving conflicts. Class DD calls f1() if it wants D11::f() and f2() if it wants D12::f(). If you define the wrappers inline you'll probably get about zero overhead.
Of course, if you can change D11 and D12 then you can do the same trick inside these classes, but often that is not the case.
A: In addition to what has already been said about multiple and virtual inheritance(s), there is a very interesting article on Dr Dobb's Journal: Multiple Inheritance Considered Useful
A: Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.
Consider the following scenario:
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};
The above class hierarchy results in the "dreaded diamond" which looks like this:
A
/ \
B C
\ /
D
An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A.
When you have this scenario, you have the possibility of ambiguity. What happens when you do this:
D d;
d.Foo(); // is this B's Foo() or C's Foo() ??
Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};
This means that there is only one "instance" of A included in the hierarchy. Hence
D d;
d.Foo(); // no longer ambiguous
This is a mini summary. For more information, have a read of this and this. A good example is also available here.
A: Explaining multiple-inheritance with virtual bases requires a knowledge of the C++ object model. And explaining the topic clearly is best done in an article and not in a comment box.
The best, readable explanation I found that solved all my doubts on this subject was this article: http://www.phpcompiler.org/articles/virtualinheritance.html
You really won't need to read anything else on the topic (unless you are a compiler writer) after reading that...
A: Diamond inheritance runnable usage example
This example shows how to use a virtual base class in the typical scenario: to solve diamond inheritance problems.
Consider the following working example:
main.cpp
#include <cassert>
class A {
public:
A(){}
A(int i) : i(i) {}
int i;
virtual int f() = 0;
virtual int g() = 0;
virtual int h() = 0;
};
class B : public virtual A {
public:
B(int j) : j(j) {}
int j;
virtual int f() { return this->i + this->j; }
};
class C : public virtual A {
public:
C(int k) : k(k) {}
int k;
virtual int g() { return this->i + this->k; }
};
class D : public B, public C {
public:
D(int i, int j, int k) : A(i), B(j), C(k) {}
virtual int h() { return this->i + this->j + this->k; }
};
int main() {
D d = D(1, 2, 4);
assert(d.f() == 3);
assert(d.g() == 5);
assert(d.h() == 7);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
If we remove the virtual into:
class B : public virtual A
we would get a wall of errors about GCC being unable to resolve D members and methods that were inherited twice via A:
main.cpp:27:7: warning: virtual base ‘A’ inaccessible in ‘D’ due to ambiguity [-Wextra]
27 | class D : public B, public C {
| ^
main.cpp: In member function ‘virtual int D::h()’:
main.cpp:30:40: error: request for member ‘i’ is ambiguous
30 | virtual int h() { return this->i + this->j + this->k; }
| ^
main.cpp:7:13: note: candidates are: ‘int A::i’
7 | int i;
| ^
main.cpp:7:13: note: ‘int A::i’
main.cpp: In function ‘int main()’:
main.cpp:34:20: error: invalid cast to abstract class type ‘D’
34 | D d = D(1, 2, 4);
| ^
main.cpp:27:7: note: because the following virtual functions are pure within ‘D’:
27 | class D : public B, public C {
| ^
main.cpp:8:21: note: ‘virtual int A::f()’
8 | virtual int f() = 0;
| ^
main.cpp:9:21: note: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
main.cpp:34:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’
34 | D d = D(1, 2, 4);
| ^
In file included from /usr/include/c++/9/cassert:44,
from main.cpp:1:
main.cpp:35:14: error: request for member ‘f’ is ambiguous
35 | assert(d.f() == 3);
| ^
main.cpp:8:21: note: candidates are: ‘virtual int A::f()’
8 | virtual int f() = 0;
| ^
main.cpp:17:21: note: ‘virtual int B::f()’
17 | virtual int f() { return this->i + this->j; }
| ^
In file included from /usr/include/c++/9/cassert:44,
from main.cpp:1:
main.cpp:36:14: error: request for member ‘g’ is ambiguous
36 | assert(d.g() == 5);
| ^
main.cpp:9:21: note: candidates are: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
main.cpp:24:21: note: ‘virtual int C::g()’
24 | virtual int g() { return this->i + this->k; }
| ^
main.cpp:9:21: note: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
./main.out
Tested on GCC 9.3.0, Ubuntu 20.04.
A: About the memory layout
As a side note, the problem with the Dreaded Diamond is that the base class is present multiple times. So with regular inheritance, you believe you have:
A
/ \
B C
\ /
D
But in the memory layout, you have:
A A
| |
B C
\ /
D
This explain why when call D::foo(), you have an ambiguity problem. But the real problem comes when you want to use a member variable of A. For example, let's say we have:
class A
{
public :
foo() ;
int m_iValue ;
} ;
When you'll try to access m_iValue from D, the compiler will protest, because in the hierarchy, it'll see two m_iValue, not one. And if you modify one, say, B::m_iValue (that is the A::m_iValue parent of B), C::m_iValue won't be modified (that is the A::m_iValue parent of C).
This is where virtual inheritance comes handy, as with it, you'll get back to a true diamond layout, with not only one foo() method only, but also one and only one m_iValue.
What could go wrong?
Imagine:
*
*A has some basic feature.
*B adds to it some kind of cool array of data (for example)
*C adds to it some cool feature like an observer pattern (for example, on m_iValue).
*D inherits from B and C, and thus from A.
With normal inheritance, modifying m_iValue from D is ambiguous and this must be resolved. Even if it is, there are two m_iValues inside D, so you'd better remember that and update the two at the same time.
With virtual inheritance, modifying m_iValue from D is ok... But... Let's say that you have D. Through its C interface, you attached an observer. And through its B interface, you update the cool array, which has the side effect of directly changing m_iValue...
As the change of m_iValue is done directly (without using a virtual accessor method), the observer "listening" through C won't be called, because the code implementing the listening is in C, and B doesn't know about it...
Conclusion
If you're having a diamond in your hierarchy, it means that you have 95% probability to have done something wrong with said hierarchy.
A: Regular Inheritance
With typical 3 level non-diamond non-virtual-inheritance inheritance, when you instantiate a new most-derived-object, new is called and the size required for the object on the heap is resolved from the class type by the compiler and passed to new.
new has a signature:
_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)
And makes a call to malloc, returning the void pointer
This address is then passed to the constructor of the most derived object, which will immediately call the middle constructor and then the middle constructor will immediately call the base constructor. The base then stores a pointer to its virtual table at the start of the object and then its attributes after it. This then returns to the middle constructor which will store its virtual table pointer at the same location and then its attributes after the attributes that would have been stored by the base constructor. It then returns to the most derived constructor, which stores a pointer to its virtual table at the same location and and then stores its attributes after the attributes that would have been stored by the middle constructor.
Because the virtual table pointer is overwritten, the virtual table pointer ends up always being the one of the most derived class. Virtualness propagates towards the most derived class so if a function is virtual in the middle class, it will be virtual in the most derived class but not the base class. If you polymorphically cast an instance of the most derived class to a pointer to the base class then the compiler will not resolve this to an indirect call to the virtual table and instead will call the function directly A::function(). If a function is virtual for the type you have cast it to then it will resolve to a call into the virtual table which will always be that of the most derived class. If it is not virtual for that type then it will just call Type::function() and pass the object pointer to it, cast to Type.
Actually when I say pointer to its virtual table, it's actually always an offset of 16 into the virtual table.
vtable for Base:
.quad 0
.quad typeinfo for Base
.quad Base::CommonFunction()
.quad Base::VirtualFunction()
pointer is typically to the first function i.e.
mov edx, OFFSET FLAT:vtable for Base+16
virtual is not required again in more-derived classes if it is virtual in a less-derived class because it propagates downwards in the direction of the most derived class. But it can be used to show that the function is indeed a virtual function, without having to check the classes it inherits's type definitions. When a function is declared virtual, from that point on, only the last implementation in the inheritance chain is used, but before that, it can still be used non-virtually if the object is cast to a type of a class before that in the inheritance chain that defines that method. It can be defined non-virtually in multiple classes before it in the chain before the virtualhood begins for a method of that name and signature, and they will use their own methods when referenced (and all classes after that definition in the chain will use that definition if they do not have their own definition, as opposed to virtual, which always uses the final definition). When a method is declared virtual, it must be implemented in that class or a more derived class in the inheritance chain for the full object that was constructed in order to be used.
override is another compiler guard that says that this function is overriding something and if it isn't then throw a compiler error.
= 0 means that this is an abstract function
final prevents a virtual function from being implemented again in a more derived class and will make sure that the virtual table of the most derived class contains the final function of that class.
= default makes it explicit in documentation that the compiler will use the default implementation
= delete give a compiler error if a call to this is attempted
If you call a non-virtual function, it will resolve to the correct method definition without going through the virtual table. If you call a virtual-function that has its final definition in an inherited class then it will use its virtual table and will pass the subobject to it automatically if you don't cast the object pointer to that type when calling the method. If you call a virtual function defined in the most derived class on a pointer of that type then it will use its virtual table, which will be the one at the start of the object. If you call it on a pointer of an inherited type and the function is also virtual in that class then it will use the vtable pointer of that subobject, which in the case of the first subobject will be the same pointer as the most derived class, which will not contain a thunk as the address of the object and the subobject are the same, and therefore it's just as simple as the method automatically recasting this pointer, but in the case of a 2nd sub object, its vtable will contain a non-virtual thunk to convert the pointer of the object of inherited type to the type the implementation in the most derived class expects, which is the full object, and therefore offsets the subobject pointer to point to the full object, and in the case of base subobject, will require a virtual thunk to offset the pointer to the base to the full object, such that it can be recast by the method hidden object parameter type.
Using the object with a reference operator and not through a pointer (dereference operator) breaks polymorphism and will treat virtual methods as regular methods. This is because polymorphic casting on non-pointer types can't occur due to slicing.
Virtual Inheritance
Consider
class Base
{
int a = 1;
int b = 2;
public:
void virtual CommonFunction(){} ; //define empty method body
void virtual VirtualFunction(){} ;
};
class DerivedClass1: virtual public Base
{
int c = 3;
public:
void virtual DerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
};
class DerivedClass2 : virtual public Base
{
int d = 4;
public:
//void virtual DerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
void virtual DerivedCommonFunction2(){} ;
};
class DerivedDerivedClass : public DerivedClass1, public DerivedClass2
{
int e = 5;
public:
void virtual DerivedDerivedCommonFunction(){} ;
void virtual VirtualFunction(){} ;
};
int main () {
DerivedDerivedClass* d = new DerivedDerivedClass;
d->VirtualFunction();
d->DerivedCommonFunction();
d->DerivedCommonFunction2();
d->DerivedDerivedCommonFunction();
((DerivedClass2*)d)->DerivedCommonFunction2();
((Base*)d)->VirtualFunction();
}
Without virtually inheriting the bass class you will get an object that looks like this:
Instead of this:
I.e. there will be 2 base objects.
In the virtual diamond inheritance situation above, after new is called, it passes the address of the allocated space for the object to the most derived constructor DerivedDerivedClass::DerivedDerivedClass(), which calls Base::Base() first, which writes its vtable in the base's dedicated subobject, it then DerivedDerivedClass::DerivedDerivedClass() calls DerivedClass1::DerivedClass1(), which writes its virtual table pointer to its subobject as well as overwriting the base subobject's pointer at the end of the object by consulting the passed VTT, and then calls DerivedClass1::DerivedClass1() to do the same, and finally DerivedDerivedClass::DerivedDerivedClass() overwrites all 3 pointers with its virtual table pointer for that inherited class. This is instead of (as illustrated in the 1st image above) DerivedDerivedClass::DerivedDerivedClass() calling DerivedClass1::DerivedClass1() and that calling Base::Base() (which overwrites the virtual pointer), returning, offsetting the address to the next subobject, calling DerivedClass2::DerivedClass2() and then that also calling Base::Base(), overwriting that virtual pointer, returning and then DerivedDerivedClass constructor overwriting both virtual pointers with its virtual table pointer (in this instance, the virtual table of the most derived constructor contains 2 subtables instead of 3).
The following is all compiled in debug mode -O0 so there will be redundant assembly
main:
.LFB8:
push rbp
mov rbp, rsp
push rbx
sub rsp, 24
mov edi, 48 //pass size to new
call operator new(unsigned long) //call new
mov rbx, rax //move the address of the allocation to rbx
mov rdi, rbx //move it to rdi i.e. pass to the call
call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor] //construct on this address
mov QWORD PTR [rbp-24], rbx //store the address of the object on the stack as the d pointer variable on -O0, will be optimised off on -Ofast if the address of the pointer itself isn't taken in the code, because this address does not need to be on the stack, it can just be passed in a register to the subsequent methods
Parenthetically, if the code were DerivedDerivedClass d = DerivedDerivedClass(), the main function would look like this:
main:
push rbp
mov rbp, rsp
sub rsp, 48 // make room for and zero 48 bytes on the stack for the 48 byte object, no extra padding required as the frame is 64 bytes with `rbp` and return address of the function it calls (no stack params are passed to any function it calls), hence rsp will be aligned by 16 assuming it was aligned at the start of this frame
mov QWORD PTR [rbp-48], 0
mov QWORD PTR [rbp-40], 0
mov QWORD PTR [rbp-32], 0
mov QWORD PTR [rbp-24], 0
mov QWORD PTR [rbp-16], 0
mov QWORD PTR [rbp-8], 0
lea rax, [rbp-48] // load the address of the cleared 48 bytes
mov rdi, rax // pass the address as a pointer to the 48 bytes cleared as the first parameter to the constructor
call DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]
//address is not stored on the stack because the object is used directly -- there is no pointer variable -- d refers to the object on the stack as opposed to being a pointer
Moving back to the original example, the DerivedDerivedClass constructor:
DerivedDerivedClass::DerivedDerivedClass() [complete object constructor]:
.LFB20:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR [rbp-8], rdi
.LBB5:
mov rax, QWORD PTR [rbp-8] // object address now in rax
add rax, 32 //increment address by 32
mov rdi, rax // move object address+32 to rdi i.e. pass to call
call Base::Base() [base object constructor]
mov rax, QWORD PTR [rbp-8] //move object address to rax
mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+8 //move address of VTT+8 to edx
mov rsi, rdx //pass VTT+8 address as 2nd parameter
mov rdi, rax //object address as first (DerivedClass1 subobject)
call DerivedClass1::DerivedClass1() [base object constructor]
mov rax, QWORD PTR [rbp-8] //move object address to rax
add rax, 16 //increment object address by 16
mov edx, OFFSET FLAT:VTT for DerivedDerivedClass+24 //store address of VTT+24 in edx
mov rsi, rdx //pass address of VTT+24 as second parameter
mov rdi, rax //address of DerivedClass2 subobject as first
call DerivedClass2::DerivedClass2() [base object constructor]
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+24 //move this to edx
mov rax, QWORD PTR [rbp-8] // object address now in rax
mov QWORD PTR [rax], rdx. //store address of vtable for DerivedDerivedClass+24 at the start of the object
mov rax, QWORD PTR [rbp-8] // object address now in rax
add rax, 32 // increment object address by 32
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+120 //move this to edx
mov QWORD PTR [rax], rdx //store vtable for DerivedDerivedClass+120 at object+32 (Base)
mov edx, OFFSET FLAT:vtable for DerivedDerivedClass+72 //store this in edx
mov rax, QWORD PTR [rbp-8] //move object address to rax
mov QWORD PTR [rax+16], rdx //store vtable for DerivedDerivedClass+72 at object+16 (DerivedClass2)
mov rax, QWORD PTR [rbp-8]
mov DWORD PTR [rax+28], 5 // stores e = 5 in the object
.LBE5:
nop
leave
ret
The DerivedDerivedClass constructor calls Base::Base() with a pointer to the object offset 32. Base stores a pointer to its virtual table at the address it receives and its members after it.
Base::Base() [base object constructor]:
.LFB11:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi //stores address of object on stack (-O0)
.LBB2:
mov edx, OFFSET FLAT:vtable for Base+16 //puts vtable for Base+16 in edx
mov rax, QWORD PTR [rbp-8] //copies address of object from stack to rax
mov QWORD PTR [rax], rdx //stores it address of object
mov rax, QWORD PTR [rbp-8] //copies address of object on stack to rax again
mov DWORD PTR [rax+8], 1 //stores a = 1 in the object
mov rax, QWORD PTR [rbp-8] //junk from -O0
mov DWORD PTR [rax+12], 2 //stores b = 2 in the object
.LBE2:
nop
pop rbp
ret
DerivedDerivedClass::DerivedDerivedClass() then calls DerivedClass1::DerivedClass1() with a pointer to the object offset 0 and also passes the address of VTT for DerivedDerivedClass+8
DerivedClass1::DerivedClass1() [base object constructor]:
.LFB14:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi //address of object
mov QWORD PTR [rbp-16], rsi //address of VTT+8
.LBB3:
mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax
mov rdx, QWORD PTR [rax] //address of DerivedClass1-in-DerivedDerivedClass+24 now in rdx
mov rax, QWORD PTR [rbp-8] //address of object now in rax
mov QWORD PTR [rax], rdx //store address of DerivedClass1-in-.. in the object
mov rax, QWORD PTR [rbp-8] // address of object now in rax
mov rax, QWORD PTR [rax] //address of DerivedClass1-in.. now implicitly in rax
sub rax, 24 //address of DerivedClass1-in-DerivedDerivedClass+0 now in rax
mov rax, QWORD PTR [rax] //value of 32 now in rax
mov rdx, rax // now in rdx
mov rax, QWORD PTR [rbp-8] //address of object now in rax
add rdx, rax //address of object+32 now in rdx
mov rax, QWORD PTR [rbp-16] //address of VTT+8 now in rax
mov rax, QWORD PTR [rax+8] //derference VTT+8+8; address of DerivedClass1-in-DerivedDerivedClass+72 (Base::CommonFunction()) now in rax
mov QWORD PTR [rdx], rax //store at address object+32 (offset to Base)
mov rax, QWORD PTR [rbp-8] //store address of object in rax, return
mov DWORD PTR [rax+8], 3 //store its attribute c = 3 in the object
.LBE3:
nop
pop rbp
ret
VTT for DerivedDerivedClass:
.quad vtable for DerivedDerivedClass+24
.quad construction vtable for DerivedClass1-in-DerivedDerivedClass+24 //(DerivedClass1 uses this to write its vtable pointer)
.quad construction vtable for DerivedClass1-in-DerivedDerivedClass+72 //(DerivedClass1 uses this to overwrite the base vtable pointer)
.quad construction vtable for DerivedClass2-in-DerivedDerivedClass+24
.quad construction vtable for DerivedClass2-in-DerivedDerivedClass+72
.quad vtable for DerivedDerivedClass+120 // DerivedDerivedClass supposed to use this to overwrite Bases's vtable pointer
.quad vtable for DerivedDerivedClass+72 // DerivedDerivedClass supposed to use this to overwrite DerivedClass2's vtable pointer
//although DerivedDerivedClass uses vtable for DerivedDerivedClass+72 and DerivedDerivedClass+120 directly to overwrite them instead of going through the VTT
construction vtable for DerivedClass1-in-DerivedDerivedClass:
.quad 32
.quad 0
.quad typeinfo for DerivedClass1
.quad DerivedClass1::DerivedCommonFunction()
.quad DerivedClass1::VirtualFunction()
.quad -32
.quad 0
.quad -32
.quad typeinfo for DerivedClass1
.quad Base::CommonFunction()
.quad virtual thunk to DerivedClass1::VirtualFunction()
construction vtable for DerivedClass2-in-DerivedDerivedClass:
.quad 16
.quad 0
.quad typeinfo for DerivedClass2
.quad DerivedClass2::VirtualFunction()
.quad DerivedClass2::DerivedCommonFunction2()
.quad -16
.quad 0
.quad -16
.quad typeinfo for DerivedClass2
.quad Base::CommonFunction()
.quad virtual thunk to DerivedClass2::VirtualFunction()
vtable for DerivedDerivedClass:
.quad 32
.quad 0
.quad typeinfo for DerivedDerivedClass
.quad DerivedClass1::DerivedCommonFunction()
.quad DerivedDerivedClass::VirtualFunction()
.quad DerivedDerivedClass::DerivedDerivedCommonFunction()
.quad 16
.quad -16
.quad typeinfo for DerivedDerivedClass
.quad non-virtual thunk to DerivedDerivedClass::VirtualFunction()
.quad DerivedClass2::DerivedCommonFunction2()
.quad -32
.quad 0
.quad -32
.quad typeinfo for DerivedDerivedClass
.quad Base::CommonFunction()
.quad virtual thunk to DerivedDerivedClass::VirtualFunction()
virtual thunk to DerivedClass1::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK0
virtual thunk to DerivedClass2::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK1
virtual thunk to DerivedDerivedClass::VirtualFunction():
mov r10, QWORD PTR [rdi]
add rdi, QWORD PTR [r10-32]
jmp .LTHUNK2
non-virtual thunk to DerivedDerivedClass::VirtualFunction():
sub rdi, 16
jmp .LTHUNK3
.set .LTHUNK0,DerivedClass1::VirtualFunction()
.set .LTHUNK1,DerivedClass2::VirtualFunction()
.set .LTHUNK2,DerivedDerivedClass::VirtualFunction()
.set .LTHUNK3,DerivedDerivedClass::VirtualFunction()
Each inherited class has its own construction virtual table and the most derived class, DerivedDerivedClass, has a virtual table with a subtable for each, and it uses the pointer to the subtable to overwrite construction vtable pointer that the inherited class's constructor stored for each subobject. Each virtual method that needs a thunk (virtual thunk offsets the object pointer from the base to the start of the object and a non-virtual thunk offsets the object pointer from an inherited class's object that isn't the base object to the start of the whole object of the type DerivedDerivedClass). The DerivedDerivedClass constructor also uses a virtual table table (VTT) as a serial list of all the virtual table pointers that it needs to use and passes it to each constructor (along with the subobject address that the constructor is for), which they use to overwrite their and the base's vtable pointer.
DerivedDerivedClass::DerivedDerivedClass() then passes the address of the object+16 and the address of VTT for DerivedDerivedClass+24 to DerivedClass2::DerivedClass2() whose assembly is identical to DerivedClass1::DerivedClass1() except for the line mov DWORD PTR [rax+8], 3 which obviously has a 4 instead of 3 for d = 4.
After this, it replaces all 3 virtual table pointers in the object with pointers to offsets in DerivedDerivedClass's vtable to the representation for that class.
The call to d->VirtualFunction() in main:
mov rax, QWORD PTR [rbp-24] //store pointer to object (and hence vtable pointer) in rax
mov rax, QWORD PTR [rax] //dereference this pointer to vtable pointer and store virtual table pointer in rax
add rax, 8 // add 8 to the pointer to get the 2nd function pointer in the table
mov rdx, QWORD PTR [rax] //dereference this pointer to get the address of the method to call
mov rax, QWORD PTR [rbp-24] //restore pointer to object in rax (-O0 is inefficient, yes)
mov rdi, rax //pass object to the method
call rdx
d->DerivedCommonFunction();:
mov rax, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rdx]
mov rdx, QWORD PTR [rdx]
mov rdi, rax //pass object to method
call rdx //call the first function in the table
d->DerivedCommonFunction2();:
mov rax, QWORD PTR [rbp-24] //get the object pointer
lea rdx, [rax+16] //get the address of the 2nd subobject in the object
mov rax, QWORD PTR [rbp-24] //get the object pointer
mov rax, QWORD PTR [rax+16] // get the vtable pointer of the 2nd subobject
add rax, 8 //call the 2nd function in this table
mov rax, QWORD PTR [rax] //get the address of the 2nd function
mov rdi, rdx //call it and pass the 2nd subobject to it
call rax
d->DerivedDerivedCommonFunction();:
mov rax, QWORD PTR [rbp-24] //get the object pointer
mov rax, QWORD PTR [rax] //get the vtable pointer
add rax, 16 //get the 3rd function in the first virtual table (which is where virtual functions that that first appear in the most derived class go, because they belong to the full object which uses the virtual table pointer at the start of the object)
mov rdx, QWORD PTR [rax] //get the address of the object
mov rax, QWORD PTR [rbp-24]
mov rdi, rax //call it and pass the whole object to it
call rdx
((DerivedClass2*)d)->DerivedCommonFunction2();:
//it casts the object to its subobject and calls the corresponding method in its virtual table, which will be a non-virtual thunk
cmp QWORD PTR [rbp-24], 0
je .L14
mov rax, QWORD PTR [rbp-24]
add rax, 16
jmp .L15
.L14:
mov eax, 0
.L15:
cmp QWORD PTR [rbp-24], 0
cmp QWORD PTR [rbp-24], 0
je .L18
mov rdx, QWORD PTR [rbp-24]
add rdx, 16
jmp .L19
.L18:
mov edx, 0
.L19:
mov rdx, QWORD PTR [rdx]
add rdx, 8
mov rdx, QWORD PTR [rdx]
mov rdi, rax
call rdx
((Base*)d)->VirtualFunction();:
//it casts the object to its subobject and calls the corresponding function in its virtual table, which will be a virtual thunk
cmp QWORD PTR [rbp-24], 0
je .L20
mov rax, QWORD PTR [rbp-24]
mov rax, QWORD PTR [rax]
sub rax, 24
mov rax, QWORD PTR [rax]
mov rdx, rax
mov rax, QWORD PTR [rbp-24]
add rax, rdx
jmp .L21
.L20:
mov eax, 0
.L21:
cmp QWORD PTR [rbp-24], 0
cmp QWORD PTR [rbp-24], 0
je .L24
mov rdx, QWORD PTR [rbp-24]
mov rdx, QWORD PTR [rdx]
sub rdx, 24
mov rdx, QWORD PTR [rdx]
mov rcx, rdx
mov rdx, QWORD PTR [rbp-24]
add rdx, rcx
jmp .L25
.L24:
mov edx, 0
.L25:
mov rdx, QWORD PTR [rdx]
add rdx, 8
mov rdx, QWORD PTR [rdx]
mov rdi, rax
call rdx
A:
A virtual base class is a class that
cannot be instantiated : you cannot
create direct object out of it.
I think you are confusing two very different things. Virtual inheritance is not the same thing as an abstract class. Virtual inheritance modifies the behaviour of function calls; sometimes it resolves function calls that otherwise would be ambiguous, sometimes it defers function call handling to a class other than that one would expect in a non-virtual inheritance.
A: It means a call to a virtual function will be forwarded to the "right" class.
C++ FAQ Lite FTW.
In short, it is often used in multiple-inheritance scenarios, where a "diamond" hierarchy is formed. Virtual inheritance will then break the ambiguity created in the bottom class, when you call function in that class and the function needs to be resolved to either class D1 or D2 above that bottom class. See the FAQ item for a diagram and details.
It is also used in sister delegation, a powerful feature (though not for the faint of heart). See this FAQ.
Also see Item 40 in Effective C++ 3rd edition (43 in 2nd edition).
A: You're being a little confusing. I dont' know if you're mixing up some concepts.
You don't have a virtual base class in your OP. You just have a base class.
You did virtual inheritance. This is usually used in multiple inheritance so that multiple derived classes use the members of the base class without reproducing them.
A base class with a pure virtual function is not be instantiated. this requires the syntax that Paul gets at. It is typically used so that derived classes must define those functions.
I don't want to explain any more about this because I don't totally get what you're asking.
A: Virtual classes are not the same as virtual inheritance. Virtual classes you cannot instantiate, virtual inheritance is something else entirely.
Wikipedia describes it better than I can. http://en.wikipedia.org/wiki/Virtual_inheritance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "462"
} |
Q: How to enable multisampling for a wxWidgets OpenGL program? Multisampling is a way of applying full screen anti-aliasing (FSAA) in 3D applications. I need to use multisampling in my OpenGL program, which is currently embedded in a wxWidgets GUI. Is there a way to do this? Please respond only if you know the detailed steps to achieve this.
I'm aware of enabling multisampling using WGL (Win32 extensions to OpenGL). However, since my OpenGL program isn't written in MFC (and I want the code to be multi-platform portable), that's not an option for me.
A: I finally got Multisampling working with my wxWidgets OpenGL program. It's a bit messy right now, but here's how:
wxWidgets doesn't have Multisampling support in their stable releases right now (latest version at this time is 2.8.8). But, it's available as a patch and also through their daily snapshot. (The latter is heartening, since it means that the patch has been accepted and should appear in later stable releases if there are no issues.)
So, there are 2 options:
*
*Download and build from their daily snapshot.
*Get the patch for your working wxWidgets installation.
I found the 2nd option to be less cumbersome, since I don't want to disturb my working installation as much as possible. If you don't know how to patch on Windows, see this.
At the very least, for Windows, the patch will modify the following files:
$(WX_WIDGETS_ROOT)/include/wx/glcanvas.h
$(WX_WIDGETS_ROOT)/include/wx/msw/glcanvas.h
$(WX_WIDGETS_ROOT)/src/msw/glcanvas.cpp
After patching, recompile the wxWidgets libraries.
To enable multisampling in your wxWidgets OpenGL program, minor changes to the code are required.
An attribute list needs to be passed to the wxGLCanvas constructor:
int attribList[] = {WX_GL_RGBA,
WX_GL_DOUBLEBUFFER,
WX_GL_SAMPLE_BUFFERS, GL_TRUE, // Multi-sampling
WX_GL_DEPTH_SIZE, 16,
0, 0};
If you were already using an attribute list, then add the line with GL_SAMPLE_BUFFERS, GL_TRUE to it. Else, add this attribute list definition to your code.
Then modify your wxGLCanvas constructor to take this attribute list as a parameter:
myGLFrame::myGLFrame // Derived from wxGLCanvas
(
wxWindow *parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name
)
: wxGLCanvas(parent, (wxGLCanvas*) NULL, id, pos, size, style, name, attribList)
{
// ...
}
After the wxGLCanvas element is created, multisampling is turned on by default. To disable or enable it at will, use the related OpenGL calls:
glEnable(GL_MULTISAMPLE);
glDisable(GL_MULTISAMPLE);
Multisampling should now work with the wxWidgets OpenGL program. Hopefully, it should be supported in the stable release of wxWidgets soon, making this information irrelevant :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there a Unix utility to prepend timestamps to stdin? I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like:
cat somefile.txt | prepend-timestamp
(Before you answer sed, I tried this:
cat somefile.txt | sed "s/^/`date`/"
But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)
A: annotate, available via that link or as annotate-output in the Debian devscripts package.
$ echo -e "a\nb\nc" > lines
$ annotate-output cat lines
17:00:47 I: Started cat lines
17:00:47 O: a
17:00:47 O: b
17:00:47 O: c
17:00:47 I: Finished with exitcode 0
A: Distilling the given answers to the simplest one possible:
unbuffer $COMMAND | ts
On Ubuntu, they come from the expect-dev and moreutils packages.
sudo apt-get install expect-dev moreutils
A: I'm not an Unix guy, but I think you can use
gawk '{print strftime("%d/%m/%y",systime()) $0 }' < somefile.txt
A: #! /bin/sh
unbuffer "$@" | perl -e '
use Time::HiRes (gettimeofday);
while(<>) {
($s,$ms) = gettimeofday();
print $s . "." . $ms . " " . $_;
}'
A:
$ cat somefile.txt | sed "s/^/`date`/"
you can do this (with gnu/sed):
$ some-command | sed "x;s/.*/date +%T/e;G;s/\n/ /g"
example:
$ { echo 'line1'; sleep 2; echo 'line2'; } | sed "x;s/.*/date +%T/e;G;s/\n/ /g"
20:24:22 line1
20:24:24 line2
of course, you can use other options of the program date. just replace date +%T with what you need.
A: How about this?
cat somefile.txt | perl -pne 'print scalar(localtime()), " ";'
Judging from your desire to get live timestamps, maybe you want to do live updating on a log file or something? Maybe
tail -f /path/to/log | perl -pne 'print scalar(localtime()), " ";' > /path/to/log-with-timestamps
A: ts from moreutils will prepend a timestamp to every line of input you give it. You can format it using strftime too.
$ echo 'foo bar baz' | ts
Mar 21 18:07:28 foo bar baz
$ echo 'blah blah blah' | ts '%F %T'
2012-03-21 18:07:30 blah blah blah
$
To install it:
sudo apt-get install moreutils
A: Here's my awk solution (from a Windows/XP system with MKS Tools installed in the C:\bin directory). It is designed to add the current date and time in the form mm/dd hh:mm to the beginning of each line having fetched that timestamp from the system as each line is read. You could, of course, use the BEGIN pattern to fetch the timestamp once and add that timestamp to each record (all the same). I did this to tag a log file that was being generated to stdout with the timestamp at the time the log message was generated.
/"pattern"/ "C\:\\\\bin\\\\date '+%m/%d %R'" | getline timestamp;
print timestamp, $0;
where "pattern" is a string or regex (without the quotes) to be matched in the input line, and is optional if you wish to match all input lines.
This should work on Linux/UNIX systems as well, just get rid of the C\:\\bin\\ leaving the line
"date '+%m/%d %R'" | getline timestamp;
This, of course, assumes that the command "date" gets you to the standard Linux/UNIX date display/set command without specific path information (that is, your environment PATH variable is correctly configured).
A: Mixing some answers above from natevw and Frank Ch. Eigler.
It has milliseconds, performs better than calling a external date command each time and perl can be found in most of the servers.
tail -f log | perl -pne '
use Time::HiRes (gettimeofday);
use POSIX qw(strftime);
($s,$ms) = gettimeofday();
print strftime "%Y-%m-%dT%H:%M:%S+$ms ", gmtime($s);
'
Alternative version with flush and read in a loop:
tail -f log | perl -pne '
use Time::HiRes (gettimeofday); use POSIX qw(strftime);
$|=1;
while(<>) {
($s,$ms) = gettimeofday();
print strftime "%Y-%m-%dT%H:%M:%S+$ms $_", gmtime($s);
}'
A: Could try using awk:
<command> | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }'
You may need to make sure that <command> produces line buffered output, i.e. it flushes its output stream after each line; the timestamp awk adds will be the time that the end of the line appeared on its input pipe.
If awk shows errors, then try gawk instead.
A: Kieron's answer is the best one so far. If you have problems because the first program is buffering its out you can use the unbuffer program:
unbuffer <command> | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; }'
It's installed by default on most linux systems. If you need to build it yourself it is part of the expect package
http://expect.nist.gov
A: Just gonna throw this out there: there are a pair of utilities in daemontools called tai64n and tai64nlocal that are made for prepending timestamps to log messages.
Example:
cat file | tai64n | tai64nlocal
A: Use the read(1) command to read one line at a time from standard input, then output the line prepended with the date in the format of your choosing using date(1).
$ cat timestamp
#!/bin/sh
while read line
do
echo `date` $line
done
$ cat somefile.txt | ./timestamp
A: caerwyn's answer can be run as a subroutine, which would prevent the new processes per line:
timestamp(){
while read line
do
echo `date` $line
done
}
echo testing 123 |timestamp
A: Disclaimer: the solution I am proposing is not a Unix built-in utility.
I faced a similar problem a few days ago. I did not like the syntax and limitations of the solutions above, so I quickly put together a program in Go to do the job for me.
You can check the tool here: preftime
There are prebuilt executables for Linux, MacOS, and Windows in the Releases section of the GitHub project.
The tool handles incomplete output lines and has (from my point of view) a more compact syntax.
<command> | preftime
It's not ideal, but I though I'd share it in case it helps someone.
A: The other answers mostly work, but have some drawbacks. In particular:
*
*Many require installing a command not commonly found on linux systems, which may not be possible or convenient.
*Since they use pipes, they don't put timestamps on stderr, and lose the exit status.
*If you use multiple pipes for stderr and stdout, then some do not have atomic printing, leading to intermingled lines of output like [timestamp] [timestamp] stdout line \nstderr line
*Buffering can cause problems, and unbuffer requires an extra dependency.
To solve (4), we can use stdbuf -i0 -o0 -e0 which is generally available on most linux systems (see How to make output of any shell command unbuffered?).
To solve (3), you just need to be careful to print the entire line at a time.
*
*Bad: ruby -pe 'print Time.now.strftime(\"[%Y-%m-%d %H:%M:%S] \")' (Prints the timestamp, then prints the contents of $_.)
*Good: ruby -pe '\$_ = Time.now.strftime(\"[%Y-%m-%d %H:%M:%S] \") + \$_' (Alters $_, then prints it.)
To solve (2), we need to use multiple pipes and save the exit status:
alias tslines-pipe="stdbuf -i0 -o0 ruby -pe '\$_ = Time.now.strftime(\"[%Y-%m-%d %H:%M:%S] \") + \$_'"
function tslines() (
stdbuf -o0 -e0 "$@" 2> >(tslines-pipe) > >(tslines-pipe)
status="$?"
exit $status
)
Then you can run a command with tslines some command --options.
This almost works, except sometimes one of the pipes takes slightly longer to exit and the tslines function has exited, so the next prompt has printed. For example, this command seems to print all the output after the prompt for the next line has appeared, which can be a bit confusing:
tslines bash -c '(for (( i=1; i<=20; i++ )); do echo stderr 1>&2; echo stdout; done)'
There needs to be some coordination method between the two pipe processes and the tslines function. There are presumably many ways to do this. One way I found is to have the pipes send some lines to a pipe that the main function can listen to, and only exit after it's received data from both pipe handlers. Putting that together:
alias tslines-pipe="stdbuf -i0 -o0 ruby -pe '\$_ = Time.now.strftime(\"[%Y-%m-%d %H:%M:%S] \") + \$_'"
function tslines() (
# Pick a random name for the pipe to prevent collisions.
pipe="/tmp/pipe-$RANDOM"
# Ensure the pipe gets deleted when the method exits.
trap "rm -f $pipe" EXIT
# Create the pipe. See https://www.linuxjournal.com/content/using-named-pipes-fifos-bash
mkfifo "$pipe"
# echo will block until the pipe is read.
stdbuf -o0 -e0 "$@" 2> >(tslines-pipe; echo "done" >> $pipe) > >(tslines-pipe; echo "done" >> $pipe)
status="$?"
# Wait until we've received data from both pipe commands before exiting.
linecount=0
while [[ $linecount -lt 2 ]]; do
read line
if [[ "$line" == "done" ]]; then
((linecount++))
fi
done < "$pipe"
exit $status
)
That synchronization mechanism feels a bit convoluted; hopefully there's a simpler way to do it.
A: doing it with date and tr and xargs on OSX:
alias predate="xargs -I{} sh -c 'date +\"%Y-%m-%d %H:%M:%S\" | tr \"\n\" \" \"; echo \"{}\"'"
<command> | predate
if you want milliseconds:
alias predate="xargs -I{} sh -c 'date +\"%Y-%m-%d %H:%M:%S.%3N\" | tr \"\n\" \" \"; echo \"{}\"'"
but note that on OSX, date doesn't give you the %N option, so you'll need to install gdate (brew install coreutils) and so finally arrive at this:
alias predate="xargs -I{} sh -c 'gdate +\"%Y-%m-%d %H:%M:%S.%3N\" | tr \"\n\" \" \"; echo \"{}\"'"
A: No need to specify all the parameters in strftime() unless you really want to customize the outputting format :
echo "abc 123 xyz\njan 765 feb" \
\
| gawk -Sbe 'BEGIN {_=strftime()" "} sub("^",_)'
Sat Apr 9 13:14:53 EDT 2022 abc 123 xyz
Sat Apr 9 13:14:53 EDT 2022 jan 765 feb
works the same if you have mawk 1.3.4. Even on awk-variants without the time features, a quick getline could emulate it :
echo "abc 123 xyz\njan 765 feb" \
\
| mawk2 'BEGIN { (__="date")|getline _;
close(__)
_=_" " } sub("^",_)'
Sat Apr 9 13:19:38 EDT 2022 abc 123 xyz
Sat Apr 9 13:19:38 EDT 2022 jan 765 feb
If you wanna skip all that getline and BEGIN { }, then something like this :
mawk2 'sub("^",_" ")' \_="$(date)"
A: If the value you are prepending is the same on every line, fire up emacs with the file, then:
Ctrl + <space>
at the beginning of the of the file (to mark that spot), then scroll down to the beginning of the last line (Alt + > will go to the end of file... which probably will involve the Shift key too, then Ctrl + a to go to the beginning of that line) and:
Ctrl + x r t
Which is the command to insert at the rectangle you just specified (a rectangle of 0 width).
2008-8-21 6:45PM <enter>
Or whatever you want to prepend... then you will see that text prepended to every line within the 0 width rectangle.
UPDATE: I just realized you don't want the SAME date, so this won't work... though you may be able to do this in emacs with a slightly more complicated custom macro, but still, this kind of rectangle editing is pretty nice to know about...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "181"
} |
Q: What is the difference between Ruby 1.8 and Ruby 1.9 I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?
A: Many now recommend The Ruby Programming Language over the Pickaxe - more to the point, it has all the details of the 1.8/1.9 differences.
A: Sam Ruby has a cool slideshow that outline the differences.
In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful.
Ruby 1.9 - Major Features
*
*Performance
*Threads/Fibers
*Encoding/Unicode
*gems is (mostly) built-in now
*if statements do not introduce scope in Ruby.
What's changed?
Single character strings.
Ruby 1.9
irb(main):001:0> ?c
=> "c"
Ruby 1.8.6
irb(main):001:0> ?c
=> 99
String index.
Ruby 1.9
irb(main):001:0> "cat"[1]
=> "a"
Ruby 1.8.6
irb(main):001:0> "cat"[1]
=> 97
{"a","b"} No Longer Supported
Ruby 1.9
irb(main):002:0> {1,2}
SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC
Ruby 1.8.6
irb(main):001:0> {1,2}
=> {1=>2}
Action: Convert to {1 => 2}
Array.to_s Now Contains Punctuation
Ruby 1.9
irb(main):001:0> [1,2,3].to_s
=> "[1, 2, 3]"
Ruby 1.8.6
irb(main):001:0> [1,2,3].to_s
=> "123"
Action: Use .join instead
Colon No Longer Valid In When Statements
Ruby 1.9
irb(main):001:0> case 'a'; when /\w/: puts 'word'; end
SyntaxError: (irb):1: syntax error, unexpected ':',
expecting keyword_then or ',' or ';' or '\n'
Ruby 1.8.6
irb(main):001:0> case 'a'; when /\w/: puts 'word'; end
word
Action: Use semicolon, then, or newline
Block Variables Now Shadow Local Variables
Ruby 1.9
irb(main):001:0> i=0; [1,2,3].each {|i|}; i
=> 0
irb(main):002:0> i=0; for i in [1,2,3]; end; i
=> 3
Ruby 1.8.6
irb(main):001:0> i=0; [1,2,3].each {|i|}; i
=> 3
Hash.index Deprecated
Ruby 1.9
irb(main):001:0> {1=>2}.index(2)
(irb):18: warning: Hash#index is deprecated; use Hash#key
=> 1
irb(main):002:0> {1=>2}.key(2)
=> 1
Ruby 1.8.6
irb(main):001:0> {1=>2}.index(2)
=> 1
Action: Use Hash.key
Fixnum.to_sym Now Gone
Ruby 1.9
irb(main):001:0> 5.to_sym
NoMethodError: undefined method 'to_sym' for 5:Fixnum
Ruby 1.8.6
irb(main):001:0> 5.to_sym
=> nil
(Cont'd) Ruby 1.9
# Find an argument value by name or index.
def [](index)
lookup(index.to_sym)
end
svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb
Hash Keys Now Unordered
Ruby 1.9
irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}
=> {:a=>"a", :c=>"c", :b=>"b"}
Ruby 1.8.6
irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}
=> {:a=>"a", :b=>"b", :c=>"c"}
Order is insertion order
Stricter Unicode Regular Expressions
Ruby 1.9
irb(main):001:0> /\x80/u
SyntaxError: (irb):2: invalid multibyte escape: /\x80/
Ruby 1.8.6
irb(main):001:0> /\x80/u
=> /\x80/u
tr and Regexp Now Understand Unicode
Ruby 1.9
unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT).
gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR).
gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]}
pack and unpack
Ruby 1.8.6
def xchr(escape=true)
n = XChar::CP1252[self] || self
case n when *XChar::VALID
XChar::PREDEFINED[n] or
(n>128 ? n.chr : (escape ? "&##{n};" : [n].pack('U*')))
else
Builder::XChar::REPLACEMENT_CHAR
end
end
unpack('U*').map {|n| n.xchr(escape)}.join
BasicObject More Brutal Than BlankSlate
Ruby 1.9
irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f
NameError: uninitialized constant C::Math
Ruby 1.8.6
irb(main):001:0> require 'blankslate'
=> true
irb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f
=> 3.14159265358979
Action: Use ::Math::PI
Delegation Changes
Ruby 1.9
irb(main):002:0> class C < SimpleDelegator; end
=> nil
irb(main):003:0> C.new('').class
=> String
Ruby 1.8.6
irb(main):002:0> class C < SimpleDelegator; end
=> nil
irb(main):003:0> C.new('').class
=> C
irb(main):004:0>
Defect 17700
Use of $KCODE Produces Warnings
Ruby 1.9
irb(main):004:1> $KCODE = 'UTF8'
(irb):4: warning: variable $KCODE is no longer effective; ignored
=> "UTF8"
Ruby 1.8.6
irb(main):001:0> $KCODE = 'UTF8'
=> "UTF8"
instance_methods Now an Array of Symbols
Ruby 1.9
irb(main):001:0> {}.methods.sort.last
=> :zip
Ruby 1.8.6
irb(main):001:0> {}.methods.sort.last
=> "zip"
Action: Replace instance_methods.include? with method_defined?
Source File Encoding
Basic
# coding: utf-8
Emacs
# -*- encoding: utf-8 -*-
Shebang
#!/usr/local/rubybook/bin/ruby
# encoding: utf-8
Real Threading
*
*Race Conditions
*Implicit Ordering Assumptions
*Test Code
What's New?
Alternate Syntax for Symbol as Hash Keys
Ruby 1.9
{a: b}
redirect_to action: show
Ruby 1.8.6
{:a => b}
redirect_to :action => show
Block Local Variables
Ruby 1.9
[1,2].each {|value; t| t=value*value}
Inject Methods
Ruby 1.9
[1,2].inject(:+)
Ruby 1.8.6
[1,2].inject {|a,b| a+b}
to_enum
Ruby 1.9
short_enum = [1, 2, 3].to_enum
long_enum = ('a'..'z').to_enum
loop do
puts "#{short_enum.next} #{long_enum.next}"
end
No block? Enum!
Ruby 1.9
e = [1,2,3].each
Lambda Shorthand
Ruby 1.9
p = -> a,b,c {a+b+c}
puts p.(1,2,3)
puts p[1,2,3]
Ruby 1.8.6
p = lambda {|a,b,c| a+b+c}
puts p.call(1,2,3)
Complex Numbers
Ruby 1.9
Complex(3,4) == 3 + 4.im
Decimal Is Still Not The Default
Ruby 1.9
irb(main):001:0> 1.2-1.1
=> 0.0999999999999999
Regex “Properties”
Ruby 1.9
/\p{Space}/
Ruby 1.8.6
/[:space:]/
Splat in Middle
Ruby 1.9
def foo(first, *middle, last)
(->a, *b, c {p a-c}).(*5.downto(1))
Fibers
Ruby 1.9
f = Fiber.new do
a,b = 0,1
Fiber.yield a
Fiber.yield b
loop do
a,b = b,a+b
Fiber.yield b
end
end
10.times {puts f.resume}
Break Values
Ruby 1.9
match =
while line = gets
next if line =~ /^#/
break line if line.find('ruby')
end
“Nested” Methods
Ruby 1.9
def toggle
def toggle
"subsequent times"
end
"first time"
end
HTH!
A: One huge difference would be the move from Matz's interpreter to YARV, a bytecode virtual machine that helps significantly with performance.
A: Some more changes:
Returning a splat singleton array:
def function
return *[1]
end
a=function
*
*ruby 1.9 : [1]
*ruby 1.8 : 1
array arguments
def function(array)
array.each { |v| p v }
end
function "1"
*
*ruby 1.8: "1"
*ruby 1.9: undefined method `each' for "1":String
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "102"
} |
Q: Unit-Testing Databases This past summer I was developing a basic ASP.NET/SQL Server CRUD app, and unit testing was one of the requirements. I ran into some trouble when I tried to test against the database. To my understanding, unit tests should be:
*
*stateless
*independent from each other
*repeatable with the same results i.e. no persisting changes
These requirements seem to be at odds with each other when developing for a database. For example, I can't test Insert() without making sure the rows to be inserted aren't there yet, thus I need to call the Delete() first. But, what if they aren't already there? Then I would need to call the Exists() function first.
My eventual solution involved very large setup functions (yuck!) and an empty test case which would run first and indicate that the setup ran without problems. This is sacrificing on the independence of the tests while maintaining their statelessness.
Another solution I found is to wrap the function calls in a transaction which can be easily rolled back, like Roy Osherove's XtUnit. This work, but it involves another library, another dependency, and it seems a little too heavy of a solution for the problem at hand.
So, what has the SO community done when confronted with this situation?
tgmdbm said:
You typically use your favourite
automated unit testing framework to
perform integration tests, which is
why some people get confused, but they
don't follow the same rules. You are
allowed to involve the concrete
implementation of many of your classes
(because they've been unit tested).
You are testing how your concrete
classes interact with each other and
with the database.
So if I read this correctly, there is really no way to effectively unit-test a Data Access Layer. Or, would a "unit test" of a Data Access Layer involve testing, say, the SQL/commands generated by the classes, independent of actual interaction with the database?
A: The usual solution to external dependencies in unit tests is to use mock objects - which is to say, libraries that mimic the behavior of the real ones against which you are testing. This is not always straightforward, and sometimes requires some ingenuity, but there are several good (freeware) mock libraries out there for .Net if you don't want to "roll your own". Two come to mind immediately:
Rhino Mocks is one that has a pretty good reputation.
NMock is another.
There are plenty of commercial mock libraries available, too. Part of writing good unit tests is actually desinging your code for them - for example, by using interfaces where it makes sense, so that you can "mock" a dependent object by implmenting a "fake" version of its interface that nonetheless behaves in a predictable way, for testing purposes.
In database mocks, this means "mocking" your own DB access layer with objects that return made up table, row, or dataset objects for your unit tests to deal with.
Where I work, we typically make our own mock libs from scratch, but that doesn't mean you have to.
A: Yeah, you should refactor your code to access Repositories and Services which access the database and you can then mock or stub those objects so that the object under test never touches the database. This is much faster than storing the state of the database and resetting it after every test!
I highly recommend Moq as your mocking framework. I've used Rhino Mocks and NMock. Moq was so simple and solved all the problems I had with the other frameworks.
A: There's no real way to unit test a database other than asserting that the tables exist, contain the expected columns, and have the appropriate constraints. But that's usually not really worth doing.
You don't typically unit test the database. You usually involve the database in integration tests.
You typically use your favourite automated unit testing framework to perform integration tests, which is why some people get confused, but they don't follow the same rules. You are allowed to involve the concrete implementation of many of your classes (because they've been unit tested). You are testing how your concrete classes interact with each other and with the database.
A: I've had the same question and have come to the same basic conclusions as the other answerers here: Don't bother unit testing the actual db communication layer, but if you want to unit test your Model functions (to ensure they're pulling data properly, formatting it properly, etc.), use some kind of dummy data source and setup tests to verify the data being retrieved.
I too find the bare-bones definition of unit testing to be a poor fit for a lot of web development activities. But this page describes some more 'advanced' unit testing models and may help to inspire some ideas for applying unit testing in various situations:
Unit Test Patterns
A: I explained a technique that I have been using for this very situation here.
The basic idea is to exercise each method in your DAL - assert your results - and when each test is complete, rollback so your database is clean (no junk/test data).
The only issue that you might not find "great" is that i typically do an entire CRUD test (not pure from the unit testing perspective) but this integration test allows you to see your CRUD + mapping code in action. This way if it breaks you will know before you fire up the application (saves me a ton of work when I'm trying to go fast)
A: DBunit
You can use this tool to export the state of a database at a given time, and then when you're unit testing, it can be rolled back to its previous state automatically at the beginning of the tests. We use it quite often where I work.
A: What you should do is run your tests from a blank copy of the database that you generate from a script. You can run your tests and then analyze the data to make sure it has exactly what it should after your tests run. Then you just delete the database, since it's a throwaway. This can all be automated, and can be considered an atomic action.
A: Testing the data layer and the database together leaves few surprises for later in the
project. But testing against the database has its problems, the main one being that
you’re testing against state shared by many tests. If you insert a line into the database
in one test, the next test can see that line as well.
What you need is a way to roll back the changes you make to the database.
The TransactionScope class is smart enough to handle very complicated transactions,
as well as nested transactions where your code under test calls commits on its own
local transaction.
Here’s a simple piece of code that shows how easy it is to add rollback ability to
your tests:
[TestFixture]
public class TrannsactionScopeTests
{
private TransactionScope trans = null;
[SetUp]
public void SetUp()
{
trans = new TransactionScope(TransactionScopeOption.Required);
}
[TearDown]
public void TearDown()
{
trans.Dispose();
}
[Test]
public void TestServicedSameTransaction()
{
MySimpleClass c = new MySimpleClass();
long id = c.InsertCategoryStandard("whatever");
long id2 = c.InsertCategoryStandard("whatever");
Console.WriteLine("Got id of " + id);
Console.WriteLine("Got id of " + id2);
Assert.AreNotEqual(id, id2);
}
}
A: If you're using LINQ to SQL as the ORM then you can generate the database on-the-fly (provided that you have enough access from the account used for the unit testing). See http://www.aaron-powell.com/blog.aspx?id=1125
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Is it possible to share a transaction between a .Net application and a COM+ object? I did some tests a while ago and never figured out how to make this work.
The ingredients:
*
*COM+ transactional object (developed in VB6)
*.Net web application (with transaction) in IIS that...
makes a call to the COM+ component
updates a row in a SQL database
Testing:
Run the .Net application and force an exception.
Result:
The update made from the .Net application rolls back.
The update made by the COM+ object does not roll back.
If I call the COM+ object from an old ASP page the rollback works.
I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.
A: Because VB and .NET will use different SQL connections (and there is no way to make ADO and ADO.NET share the same connection), your only possibility is to enlist the DTC (Distributed Transaction Coordinator). The DTC will coordinates the two independent transactions so they commit or are rolled-back together.
From .NET, EnterpriseServices manages COM+ functionality, such as the DTC. In .NET 2.0 and forward, you can use the System.Transactions namespace, which makes things a little nicer. I think something like this should work (untested code):
void SomeMethod()
{
EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full;
using (TransactionScope s = new TransactionScope(e))
{
MyComPlusClass o = new MyComPlusClass();
o.SomeTransactionalMethod();
}
}
I am not familiar enough with this to give you more advice at this point.
On the COM+ side, your object needs to be configured to use (most likely "require") a distributed transaction. You can do that from COM+ Explorer, by going to your object's Properties, selecting the Transaction tab, and clicking on "Required". I don't remember if you can do this from code as well; VB6 was created before COM+ was released, so it doesn't fully support everything COM+ does (its transactional support was meant for COM+'s predecessor, called MS Transaction Server).
If everything works correctly, your COM+ object should be enlisting in the existing Context created by your .NET code.
You can use the "Distributed Transaction Coordinator\Transaction List" node in "Component Services" to check and see the distributed transaction being created during the call.
Be aware that you cannot see the changes from the COM+ component reflected on data queries from the .NET side until the Transaction is committed! In fact, it is possible to deadlock! Remember that DTC will make sure that the two transactions are paired, but they are still separate database transactions.
A: How are you implementing this? If you are using EnterpriseServices to manage the .NET transaction, then both transactions should get rolled back, since you're using the same context for them both.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What is the difference between #include and #include "filename"? What is the difference between using angle brackets and quotes in an include directive?
*
*#include <filename>
*#include "filename"
A: The only way to know is to read your implementation's documentation.
In the C standard, section 6.10.2, paragraphs 2 to 4 state:
*
*A preprocessing directive of the form
#include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.
*A preprocessing directive of the form
#include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read
#include <h-char-sequence> new-line
with the identical contained sequence (including > characters, if any) from the original
directive.
*A preprocessing directive of the form
#include pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing tokens after include in the directive are processed just as in normal text. (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.) The directive resulting after all replacements shall match one of the two previous forms. The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined into a single header name preprocessing token is implementation-defined.
Definitions:
*
*h-char: any member of the source character set except the new-line character and >
*q-char: any member of the source character set except the new-line character and "
A: The exact behavior of the preprocessor varies between compilers. The following answer applies for GCC and several other compilers.
#include <file.h> tells the compiler to search for the header in its "includes" directory, e.g. for MinGW the compiler would search for file.h in C:\MinGW\include\ or wherever your compiler is installed.
#include "file" tells the compiler to search the current directory (i.e. the directory in which the source file resides) for file.
You can use the -I flag for GCC to tell it that, when it encounters an include with angled brackets, it should also search for headers in the directory after -I. GCC will treat the directory after the flag as if it were the includes directory.
For instance, if you have a file called myheader.h in your own directory, you could say #include <myheader.h> if you called GCC with the flag -I . (indicating that it should search for includes in the current directory.)
Without the -I flag, you will have to use #include "myheader.h" to include the file, or move myheader.h to the include directory of your compiler.
A: In C++, include a file in two ways:
The first one is #include which tells the preprocessor to look for the file in the predefined default location.
This location is often an INCLUDE environment variable that denotes the path to include files.
And the second type is #include "filename" which tells the preprocessor to look for the file in the current directory first, then look for it in the predefined locations user have set up.
A: GCC documentation says the following about the difference between the two:
Both user and system header files are included using the preprocessing directive ‘#include’. It has two variants:
#include <file>
This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option (see Invocation).
#include "file"
This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. You can prepend directories to the list of quote directories with the -iquote option.
The argument of ‘#include’, whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus, #include <x/*y> specifies inclusion of a system header file named x/*y.
However, if backslashes occur within file, they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus,#include "x\n\\y"specifies a filename containing three backslashes. (Some systems interpret ‘\’ as a pathname separator. All of these also interpret ‘/’ the same way. It is most portable to use only ‘/’.)
It is an error if there is anything (other than comments) on the line after the file name.
A: The #include <filename> is used when a system file is being referred to. That is a header file that can be found at system default locations like /usr/include or /usr/local/include. For your own files that needs to be included in another program you have to use the #include "filename" syntax.
A: It does:
"mypath/myfile" is short for ./mypath/myfile
with . being either the directory of the file where the #include is contained in, and/or the current working directory of the compiler, and/or the default_include_paths
and
<mypath/myfile> is short for <defaultincludepaths>/mypath/myfile
If ./ is in <default_include_paths>, then it doesn't make a difference.
If mypath/myfile is in another include directory, the behavior is undefined.
A: The simple general rule is to use angled brackets to include header files that come with the compiler. Use double quotes to include any other header files. Most compilers do it this way.
1.9 — Header files explains in more detail about pre-processor directives. If you are a novice programmer, that page should help you understand all that. I learned it from here, and I have been following it at work.
A: #include <filename>
is used when you want to use the header file of the C/C++ system or compiler libraries. These libraries can be stdio.h, string.h, math.h, etc.
#include "path-to-file/filename"
is used when you want to use your own custom header file which is in your project folder or somewhere else.
For more information about preprocessors and header. Read C - Preprocessors.
A: Form 1 - #include < xxx >
First, looks for the presence of header file in the current directory from where directive is invoked. If not found, then it searches in the preconfigured list of standard system directories.
Form 2 - #include "xxx"
This looks for the presence of header file in the current directory from where directive is invoked.
The exact search directory list depends on the target system, how GCC is configured, and where it is installed.
You can find the search directory list of your GCC compiler by running it with -v option.
You can add additional directories to the search path by using - Idir, which causes dir to be searched after the current directory (for the quote form of the directive) and ahead of the standard system directories.
Basically, the form "xxx" is nothing but search in current directory; if not found falling back the form
A: #include <filename>
*
*The preprocessor searches in an implementation-dependent manner. It tells the compiler to search directory where system header files are held.
*This method usually use to find standard header files.
#include "filename"
*
*This tell compiler to search header files where program is running. If it was failed it behave like #include <filename> and search that header file at where system header files stored.
*This method usually used for identify user defined header files(header files which are created by user). There for don't use this if you want to call standard library because it takes more compiling time than #include <filename>.
A: #include <file>
Includes a file where the default include directory is.
#include "file"
Includes a file in the current directory in which it was compiled. Double quotes can specify a full file path to a different location as well.
A: The <file> include tells the preprocessor to search in -I directories and in predefined directories first, then in the .c file's directory. The "file" include tells the preprocessor to search the source file's directory first, and then revert to -I and predefined. All destinations are searched anyway, only the order of search is different.
The 2011 standard mostly discusses the include files in "16.2 Source file inclusion".
2 A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the
specified sequence between the < and > delimiters, and causes the
replacement of that directive by the entire contents of the header.
How the places are specified or the header identified is
implementation-defined.
3 A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the
specified sequence between the " delimiters. The named source file is
searched for in an implementation-defined manner. If this search is
not supported, or if the search fails, the directive is reprocessed as
if it read
# include <h-char-sequence> new-line
with the identical contained sequence (including > characters, if any) from the original directive.
Note that "xxx" form degrades to <xxx> form if the file is not found. The rest is implementation-defined.
A:
the " < filename > " searches in standard C library locations
whereas "filename" searches in the current directory as well.
Ideally, you would use <...> for standard C libraries and "..." for libraries that you write and are present in the current directory.
A: In general the difference is where the preprocessor searches for the header file:
#include is a preprocessor directive to include header file. Both #include are used to add or include header file in the program, but first is to include system header files and later one for user defined header files.
*
*#include <filename> is used to include the system library header file in the program, means the C/C++ preprocessor will search for the filename where the C library files are stored or predefined system header files are stored.
*#include "filename" is used to include user defined header file in the program, means the C/C++ preprocessor will search for the filename in the current directory the program is in and then follows the search path used for the #include <filename>
Check the gcc docs gcc include files
A: "" will search ./ first. Then search the default include path.
You can use command like this to print the default include path:
gcc -v -o a a.c
Here are some examples to make thing more clear:
the code a.c works
// a.c
#include "stdio.h"
int main() {
int a = 3;
printf("a = %d\n", a);
return 0;
}
the code of b.c works too
// b.c
#include <stdio.h>
int main() {
int a = 3;
printf("a = %d\n", a);
return 0;
}
but when I create a new file named stdio.h in current directory
// stdio.h
inline int foo()
{
return 10;
}
a.c will generate compile error, but b.c still works
and "", <> can be used together with the same file name. since the search path priority is different.
so d.c also works
// d.c
#include <stdio.h>
#include "stdio.h"
int main()
{
int a = 0;
a = foo();
printf("a=%d\n", a);
return 0;
}
A: The sequence of characters between < and > uniquely refer to a header, which isn't necessarily a file. Implementations are pretty much free to use the character sequence as they wish. (Mostly, however, just treat it as a file name and do a search in the include path, as the other posts state.)
If the #include "file" form is used, the implementation first looks for a file of the given name, if supported. If not (supported), or if the search fails, the implementation behaves as though the other (#include <file>) form was used.
Also, a third form exists and is used when the #include directive doesn't match either of the forms above. In this form, some basic preprocessing (such as macro expansion) is done on the "operands" of the #include directive, and the result is expected to match one of the two other forms.
A: To see the search order on your system using gcc, based on current configuration , you can execute the following command. You can find more detail on this command here
cpp -v /dev/null -o /dev/null
Apple LLVM version 10.0.0 (clang-1000.10.44.2)
Target: x86_64-apple-darwin18.0.0
Thread model: posix InstalledDir: Library/Developer/CommandLineTools/usr/bin
"/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple
x86_64-apple-macosx10.14.0 -Wdeprecated-objc-isa-usage
-Werror=deprecated-objc-isa-usage -E -disable-free -disable-llvm-verifier -discard-value-names -main-file-name null -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -fno-strict-return -masm-verbose -munwind-tables -target-cpu penryn -dwarf-column-info -debugger-tuning=lldb -target-linker-version 409.12 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/10.0.0 -isysroot
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk
-I/usr/local/include -fdebug-compilation-dir /Users/hogstrom -ferror-limit 19 -fmessage-length 80 -stack-protector 1 -fblocks -fencode-extended-block-signature -fobjc-runtime=macosx-10.14.0 -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -traditional-cpp -o - -x c /dev/null
clang -cc1 version 10.0.0 (clang-1000.10.44.2) default target x86_64-apple-darwin18.0.0 ignoring
nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/local/include"
ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/Library/Developer/CommandLineTools/usr/lib/clang/10.0.0/include
/Library/Developer/CommandLineTools/usr/include
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks (framework directory)
End of search list.
A: By the standard - yes, they are different:
*
*A preprocessing directive of the form
#include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.
*A preprocessing directive of the form
#include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read
#include <h-char-sequence> new-line
with the identical contained sequence (including > characters, if any) from the original
directive.
*A preprocessing directive of the form
#include pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing tokens after include in the directive are processed just as in normal text. (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.) The directive resulting after all replacements shall match one of the two previous forms. The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined into a single header name preprocessing token is implementation-defined.
Definitions:
*
*h-char: any member of the source character set except the new-line character and >
*q-char: any member of the source character set except the new-line character and "
Note that the standard does not tell any relation between the implementation-defined manners. The first form searches in one implementation-defined way, and the other in a (possibly other) implementation-defined way. The standard also specifies that certain include files shall be present (for example, <stdio.h>).
Formally you'd have to read the manual for your compiler, however normally (by tradition) the #include "..." form searches the directory of the file in which the #include was found first, and then the directories that the #include <...> form searches (the include path, eg system headers).
A: At least for GCC version <= 3.0, the angle-bracket form does not generate a dependency between the included file and the including one.
So if you want to generate dependency rules (using the GCC -M option for exemple), you must use the quoted form for the files that should be included in the dependency tree.
(See http://gcc.gnu.org/onlinedocs/cpp/Invocation.html )
A: For #include "" a compiler normally searches the folder of the file which contains that include and then the other folders. For #include <> the compiler does not search the current file's folder.
A: Thanks for the great answers, esp. Adam Stelmaszczyk and piCookie, and aib.
Like many programmers, I have used the informal convention of using the "myApp.hpp" form for application specific files, and the <libHeader.hpp> form for library and compiler system files, i.e. files specified in /I and the INCLUDE environment variable, for years thinking that was the standard.
However, the C standard states that the search order is implementation specific, which can make portability complicated. To make matters worse, we use jam, which automagically figures out where the include files are. You can use relative or absolute paths for your include files. i.e.
#include "../../MyProgDir/SourceDir1/someFile.hpp"
Older versions of MSVS required double backslashes (\\), but now that's not required. I don't know when it changed. Just use forward slashes for compatibility with 'nix (Windows will accept that).
If you are really worried about it, use "./myHeader.h" for an include file in the same directory as the source code (my current, very large project has some duplicate include file names scattered about--really a configuration management problem).
Here's the MSDN explanation copied here for your convenience).
Quoted form
The preprocessor searches for include files in this order:
*
*In the same directory as the file that contains the #include statement.
*In the directories of the currently opened include files, in the reverse order in which
they were opened. The search begins in the directory of the parent include file and
continues upward through the directories of any grandparent include files.
*Along the path that's specified by each /I compiler option.
*Along the paths that are specified by the INCLUDE environment variable.
Angle-bracket form
The preprocessor searches for include files in this order:
*
*Along the path that's specified by each /I compiler option.
*When compiling occurs on the command line, along the paths that are specified by the INCLUDE environment variable.
A: What differs is the locations in which the preprocessor searches for the file to be included.
*
*#include <filename> The preprocessor searches in an implementation-defined manner, normally in directories pre-designated by the compiler/IDE. This method is normally used to include header files for the C standard library and other header files associated with the target platform.
*#include "filename" The preprocessor also searches in an implementation-defined manner, but one that is normally used to include programmer-defined header files and typically includes same directory as the file containing the directive (unless an absolute path is given).
For GCC, a more complete description is available in the GCC documentation on search paths.
A: An #include with angle brackets will search an "implementation-dependent list of places" (which is a very complicated way of saying "system headers") for the file to be included.
An #include with quotes will just search for a file (and, "in an implementation-dependent manner", bleh). Which means, in normal English, it will try to apply the path/filename that you toss at it and will not prepend a system path or tamper with it otherwise.
Also, if #include "" fails, it is re-read as #include <> by the standard.
The gcc documentation has a (compiler specific) description which although being specific to gcc and not the standard, is a lot easier to understand than the attorney-style talk of the ISO standards.
A: Some good answers here make references to the C standard but forgot the POSIX standard, especially the specific behavior of the c99 (e.g. C compiler) command.
According to The Open Group Base Specifications Issue 7,
-I directory
Change the algorithm for searching for headers whose names are not absolute pathnames to look in the directory named by the directory pathname before looking in the usual places. Thus, headers whose names are enclosed in double-quotes ( "" ) shall be searched for first in the directory of the file with the #include line, then in directories named in -I options, and last in the usual places. For headers whose names are enclosed in angle brackets ( "<>" ), the header shall be searched for only in directories named in -I options and then in the usual places. Directories named in -I options shall be searched in the order specified. Implementations shall support at least ten instances of this option in a single c99 command invocation.
So, in a POSIX compliant environment, with a POSIX compliant C compiler, #include "file.h" is likely going to search for ./file.h first, where . is the directory where is the file with the #include statement, while #include <file.h>, is likely going to search for /usr/include/file.h first, where /usr/include is your system defined usual places for headers (it's seems not defined by POSIX).
A: Many of the answers here focus on the paths the compiler will search in order to find the file. While this is what most compilers do, a conforming compiler is allowed to be preprogrammed with the effects of the standard headers, and to treat, say, #include <list> as a switch, and it need not exist as a file at all.
This is not purely hypothetical. There is at least one compiler that work that way. Using #include <xxx> only with standard headers is recommended.
A: *
*#include <> is for predefined header files
If the header file is predefined then you would simply write the header file name in angular brackets, and it would look like this (assuming we have a predefined header file name iostream):
#include <iostream>
*
*#include " " is for header files the programmer defines
If you (the programmer) wrote your own header file then you would write the header file name in quotes. So, suppose you wrote a header file called myfile.h, then this is an example of how you would use the include directive to include that file:
#include "myfile.h"
A: #include <abc.h>
is used to include standard library files. So the compiler will check in the locations where standard library headers are residing.
#include "xyz.h"
will tell the compiler to include user-defined header files. So the compiler will check for these header files in the current folder or -I defined folders.
A: #include "filename" // User defined header
#include <filename> // Standard library header.
Example:
The filename here is Seller.h:
#ifndef SELLER_H // Header guard
#define SELLER_H // Header guard
#include <string>
#include <iostream>
#include <iomanip>
class Seller
{
private:
char name[31];
double sales_total;
public:
Seller();
Seller(char[], double);
char*getName();
#endif
In the class implementation (for example, Seller.cpp, and in other files that will use the file Seller.h), the header defined by the user should now be included, as follows:
#include "Seller.h"
A: The implementation-defined warnings generated by the compiler can (and will) treat system libraries differently than program libraries.
So
#include <myFilename>
-- which in effect declares that myFilename is in the system library location -- may well (and probably will) hide dead code and unused variable warnings etc, that would show up when you use:
#include "myFilename"
A: There exists two ways to write #include statement.These are:
#include"filename"
#include<filename>
The meaning of each form is
#include"mylib.h"
This command would look for the file mylib.h in the current directory as well as the specified list of directories as mentioned n the include search path that might have been set up.
#include<mylib.h>
This command would look for the file mylib.h in the specified list of directories only.
The include search path is nothing but a list of directories that would be searched for the file being included.Different C compilers let you set the search path in different manners.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2981"
} |
Q: Pushing out MSI files I have a product which has been traditionally shipped as an MSI file. It is deployed through some sort of SMS push to thousands of desktops by our various clients. The software we use to create these installers is getting long in the tooth and we are looking to replace it. We have already standardized on InstallAnywhere for most of our products as we support many operating systems. Unfortunately InstallAnywhere cannot produce MSI files.
I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe). If not, are there any open source programmes for creating MSI files?
A: If you want to create MSI files, try WiX: Windows Installer XML (WiX) toolset.
It's an addon to Visual Studio 2005 and 2008, is open-source, and Microsoft developed. You can use XML to specify and create MSI files. There is a wealth of resources available on it, and WiX 3.0 is, although in beta, is very complete.
Also, note that you don't have to start from scratch, you can decompile an existing MSI using the WiX Dark utility, modify the XML in any way you like, and then recompile it into an MSI.
A: If your clients are using SMS then you're in the clear... SMS supports EXE. You enter a command line when creating 'Programs' and clients are probably already calling msiexec to launch the MSI. Also I'm pretty sure SMS predates the MSI file format :)
However if they're using Active Directory / Group Policy Objects.. then you're SOL as that does depend on MSI format for deployment.
If you do want to stick with InstallAnywhere, there are a number of "MSI repackaging" tools available. Assuming you're looking at a basic application (device drivers might be an issue) then repackaging should be a fairly painless process.
A: Actually, with group policies, there's the ZAP file alternative, but I would recommend regardless that you learn MSI. It's not that hard, and very flexible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: .NET - Get protocol, host, and port Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:
http://www.mywebsite.com:80/pages/page1.aspx
I need to return:
http://www.mywebsite.com:80
I know I can use Request.Url.AbsoluteUri to get the complete URL, and I know I can use Request.Url.Authority to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.
Any suggestions?
A: Well if you are doing this in Asp.Net or have access to HttpContext.Current.Request
I'd say these are easier and more general ways of getting them:
var scheme = Request.Url.Scheme; // will get http, https, etc.
var host = Request.Url.Host; // will get www.mywebsite.com
var port = Request.Url.Port; // will get the port
var path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx
I hope this helps. :)
A: Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named Uri.GetLeftPart() method.
Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string output = url.GetLeftPart(UriPartial.Authority);
There is one catch to GetLeftPart(), however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of GetLeftPart() in my example above will be http://www.mywebsite.com.
If the port number had been something other than 80, it would be included in the result.
A: A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.
var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);
A: Request.Url will return you the Uri of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the Scheme property.
Sample:
Uri url = Request.Url;
string protocol = url.Scheme;
Hope this helps.
A: Even shorter way, may require newer ASP.Net:
string authority = Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)
The UriComponents enum lets you specify which component(s) of the URI you want to include.
A: The following (C#) code should do the trick
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
A: Very similar to Holger's answer. If you need to grab the URL can do something like:
Uri uri = Context.Request.Url;
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number
The Uri class provides a whole range of methods, many which I have not listed.
In my instance, I needed to grab LocalHost along with the Port Number, so this is what I did:
var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Which successfully grabbed: http://localhost:12345
A: In my case
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Authority;
works to get
https://www.mywebsite.com:80
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "265"
} |
Q: Reading from text file until EOF repeats last line The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;
}
input.txt:
10
20
30
Output:
10
20
30
30
Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
A: Without to much modifications of the original code, it could become :
while (!iFile.eof())
{
int x;
iFile >> x;
if (!iFile.eof()) break;
cerr << x << endl;
}
but I prefer the two other solutions above in general.
A: The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.
What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.
I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.
*
*0
So add a prime read and move the loop's read to the end:
int x;
iFile >> x; // prime read here
while (!iFile.eof()) {
cerr << x << endl;
iFile >> x;
}
A: I like this example, which for now, leaves out the check which you could add inside the while block:
ifstream iFile("input.txt"); // input.txt has integers, one per line
int x;
while (iFile >> x)
{
cerr << x << endl;
}
Not sure how safe it is...
A: At the end of the last line, you have a new line character, which is not read by >> operator and it is not an end of file.
Please, make an experiment and delete the new line (thelast character in file) - you will not get the duplication.
To have a flexible code and avoid unwanted effects just apply any solution given by other users.
A: int x;
ifile >> x
while (!iFile.eof())
{
cerr << x << endl;
iFile >> x;
}
A: There's an alternative approach to this:
#include <iterator>
#include <algorithm>
// ...
copy(istream_iterator<int>(iFile), istream_iterator<int>(),
ostream_iterator<int>(cerr, "\n"));
A: Just follow closely the chain of events.
*
*Grab 10
*Grab 20
*Grab 30
*Grab EOF
Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.
Try this:
while (true) {
int x;
iFile >> x;
if( iFile.eof() ) break;
cerr << x << endl;
}
By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "129"
} |
Q: Adobe AIR: Handling JSON objects from server I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.
However, in Adobe AIR, there is a restriction on using eval() for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately.
Side-note : I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now
Update:
Thanks to Theo and jsight for their answers;
One important thing I learnt today is that I can actually make use of ActionScript libraries by using the <script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script> tag extended by Adobe AIR. Check out Theo's link for more details!
A: You can find a JSON parser written in JavaScript here (source code here). You can also use the as3corelib JSON parser from JavaScript, there's a description of how to access ActionScript libraries from JavaScript here.
A: The current AIR release (v2.5) bundles a newer WebKit that has native JSON support, via JSON.stringify() and JSON.parse().
A: Have you looked at as3corelib? It appears to provide an AS3 parser for JSON data, and my hope would be that it doesn't rely upon eval (eval tends to be bad for security as you noted). There are similar libs for Javascript as well, and they tend to be the preferred way to parse json due to the security implications of calling eval on (potentially) evil data.
A: JSON is Javascript Object Notation, so if you are using Javascript you are already there!
Have a look at these links, they give examples of how to create Javascript objects from JSON:
http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)
http://betterexplained.com/articles/using-json-to-exchange-data/
If you decide to go the Flex / AS3 route, then as the jsight said, as3corelib is a good place to start.
A: I think this is possible if you use an iframe and sandbox bridge. You should be able to run eval() on downloaded code in the sandboxed iframe,
Excerpt from Adobe AIR 1.1 Doc's
"...it may be more convenient to run content in a sandboxed child frame so that the content can be run with no restrictions on eval()..."
Another related article: Building on AIR: Working with the Sandbox Bridges
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Do you write exceptions for specific issues or general exceptions? I have some code that gives a user id to a utility that then send email to that user.
emailUtil.sendEmail(userId, "foo");
public void sendEmail(String userId, String message) throws MailException {
/* ... logic that could throw a MailException */
}
MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.
My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.
Edit: As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc.
My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).
Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
A: I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.
An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).
This way you get the advantages of both, you don't have throw-clauses like:
throws SpecificException1, SpecificException2, SpecificException3 ...
a general
throws GeneralException
is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.
A: @Chris.Lively
You know you can pass a message in your exception, or even the "status codes". You are reinventing the wheel here.
A: I have found that if you need to have CODE deciding what to do based on the exception returned, create a well named exception subclassing a common base type. The message passed should be considered "human eyes only" and too fragile to make decisions upon. Let the compiler do the work!
If you need to pass this up to a higher layer through a mechanism not aware of checked exceptions, you can wrap it in a suitable named subclass of RuntimeException (MailDomainException) which can be caught up high, and the original cause acted upon.
A: In my code, I find that MOST exceptions percolate up to a UI layer where they are caught by my exception handlers which simply display a message to the user (and write to the log). It's an unexpected exception, after all.
Sometimes, I do want to catch a specific exception (as you seem to want to do). You'll probably find, however, that this is somewhat rare and that it is indicative of using exceptions to control logic -- which is inefficient (slow) and often frowned upon.
So using your example, if you want to run some special logic when the email server is not configured, you may want to add a method to the emailUtil object like:
public bool isEmailConfigured()
... call that first, instead of looking for a specific exception.
When an exception does happen, it really means that the situation was completely unexpected and the code can't handle it -- so the best you can do is report it to the user (or write it to a log or restart )
As for having an exception hierarchy vs exceptions-with-error-codes-in-them, I typically do the latter. It's easier to add new exceptions, if you just need to define a new error constant instead of a whole new class. But, it doesn't matter much as long as you try to be consistent throughout your project.
A: It depends on what your application is doing. You might want to throw individual exceptions in cases like
*
*The application is high availability
*Sending e-mail is particularly important
*The scope of the application is small and sending e-mail is a large part of it
*The application will be deployed to a site which is remote and you will only get logs for debugging
*You can recover from some subset of the exceptions encapsulated in the mailException but not others
In most cases I would say just log the text of the exception and don't waste your time granularizing already pretty granular exceptions.
A: Instead of using exceptions, I tend to return a list of status objects from methods that may have problems executing. The status objects contain a severity enum (information, warning, error, ...) a status object name like "Email Address" and a user readable message like "Badly formatted Email Address"
The calling code would then decide which to filter up to the UI and which to handle itself.
Personally, I think exceptions are strictly for when you can't implement a normal code solution. The performance hit and handling restrictions are just a bit too much for me.
Another reason for using a list of status objects is that identifying multiple errors (such as during validation) is MUCH easier. After all, you can only throw one exception which must be handled before moving on.
Imagine a user submitting an email that had a malformed destination address and contained language that you are blocking. Do you throw the malformed email exception, then, after they fix that and resubmit, throw a bad language exception? From a user experience perspective dealing with all of them at once is a better way to go.
UPDATE: combining answers
@Jonathan: My point was that I can evaluate the action, in this case sending an email, and send back multiple failure reasons. For example, "bad email address", "blank message title", etc..
With an exception, you're limited to just percolating the one problem then asking the user to resubmit at which point they find out about a second problem. This is really bad UI design.
Reinventing the wheel.. possibly. However, most applications should analyze the whole transaction in order to give the best possible information to the user. Imagine if your compiler stopped dead at the first error. You then fix the error and hit compile again only to have it stop again for a different error. What a pain in the butt. To me, that's exactly the problem with throwing exceptions and hence the reason I said to use a different mechanism.
A: I think a combination of the above is going to give you the best result.
You can throw different exceptions depending on the problem. e.g. Missing email address = ArgumentException.
But then in the UI layer you can check the exception type and, if need be, the message and then display a appropriate message to the user. I personally tend to only show a informational message to the user if a certain type of exception is thrown (UserException in my app). Of course you should scrub and verify user input as much as possible further up the stack to make sure any exceptions are generated by truly unlikely scenarios, not as a filter for malformed emails which can easily be checked with a regex.
I also wouldn't worry about the performance implications of catching an exception from user input. The only time you are going to see performance problems from exceptions is when they are being thrown and caught in a loop or similar.
A: I tend to have less Exception types, although it's not really the OO way to do it. Instead I put an enum to my custom Exceptions, which classifies the Exception. Most of the time I have a custom base Exception, which holds on to a couple of members, which can be overridden or customized in derived Exception types.
A couple of months ago I blogged about the idea of how to internationalize Exceptions. It includes some of the ideas mentioned above.
A: While you can differenciate the code execution looking the exception don't matter if it's done by the "catch exceptionType hierarchy mode" or by "if(...) else...exception code mode"
but if you are developing software wich is going to be used by other people, like a library i think it's usefull create your own exception types to notice the other people that your sofware can throw other exceptions than the normal ones, and they better catch and resolve them.
When i use a library and their methods simply launch an 'Exception' i allways wonder: What can cause this exception?, how must my program react?, if there is a javadoc maybe the cause will be explained, but mustly of times there is not a javadoc or the exception is not explained. Too much overhead witch can be avoided with a WellChossenExceptionTypeName
A: It depends on whether the code that catches the exception needs to differentiate between exceptions or whether you are just using exceptions to fail out to an error page. If you need to differentiate between a NullReference exception and your custom MailException higher up in the call stack, then spend the time and write it. But most of the time programmers just use exceptions as a catch all to throw up an error on the web page. In this case you are just wasting effort on writing a new exception.
A: I would just go by
throw new exception("WhatCausedIt")
if you want to handle your exceptions, you could pass a code instead of "WhatCausedIt" an then react to the different answers with a switch statement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Complexity of Regex substitution I didn't get the answer to this anywhere. What is the runtime complexity of a Regex match and substitution?
Edit: I work in python. But would like to know in general about most popular languages/tools (java, perl, sed).
A: Other theoretical info of possible interest.
For clarity, assume the standard definition for a regular expression
http://en.wikipedia.org/wiki/Regular_language
from the formal language theory. Practically, this means that the only building
material are alphabet symbols, operators of concatenation, alternation and
Kleene closure, along with the unit and zero constants (which appear for
group-theoretic reasons). Generally it's a good idea not to overload this term
despite the everyday practice in scripting languages which leads to
ambiguities.
There is an NFA construction that solves the matching problem for a regular
expression r and an input text t in O(|r| |t|) time and O(|r|) space, where
|-| is the length function. This algorithm was further improved by Myers
http://doi.acm.org/10.1145/128749.128755
to the time and space complexity O(|r| |t| / log |t|) by using automaton node listings and the Four Russians paradigm. This paradigm seems to be named after four Russian guys who wrote a groundbreaking paper which is not
online. However, the paradigm is illustrated in these computational biology
lecture notes
http://lyle.smu.edu/~saad/courses/cse8354/lectures/lecture5.pdf
I find it hilarious to name a paradigm by the number and
the nationality of authors instead of their last names.
The matching problem for regular expressions with added backreferences is
NP-complete, which was proven by Aho
http://portal.acm.org/citation.cfm?id=114877
by a reduction from the vertex-cover problem which is a classical NP-complete problem.
To match regular expressions with backreferences deterministically we could
employ backtracking (not unlike the Perl regex engine) to keep track of the
possible subwords of the input text t that can be assigned to the variables in
r. There are only O(|t|^2) subwords that can be assigned to any one variable
in r. If there are n variables in r, then there are O(|t|^2n) possible
assignments. Once an assignment of substrings to variables is fixed, the
problem reduces to the plain regular expression matching. Therefore the
worst-case complexity for matching regular expressions with backreferences is
O(|t|^2n).
Note however, regular expressions with backreferences are not yet
full-featured regexen.
Take, for example, the "don't care" symbol apart from any other
operators. There are several polynomial algorithms deciding whether a set of
patterns matches an input text. For example, Kucherov and Rusinowitch
http://dx.doi.org/10.1007/3-540-60044-2_46
define a pattern as a word w_1@w_2@...@w_n where each w_i is a word (not a regular expression) and "@" is a variable length "don't care" symbol not contained in either of w_i. They derive an O((|t| + |P|) log |P|) algorithm for matching a set of patterns P against an input text t, where |t| is the length of the text, and |P| is the length of all the words in P.
It would be interesting to know how these complexity measures combine and what
is the complexity measure of the matching problem for regular expressions with
backreferences, "don't care" and other interesting features of practical
regular expressions.
Alas, I haven't said a word about Python... :)
A: Depends on what you define by regex. If you allow operators of concatenation, alternative and Kleene-star, the time can actually be O(m*n+m), where m is size of a regex and n is length of the string. You do it by constructing a NFA (that is linear in m), and then simulating it by maintaining the set of states you're in and updating that (in O(m)) for every letter of input.
Things that make regex parsing difficult:
*
*parentheses and backreferences: capturing is still OK with the aforementioned algorithm, although it would get the complexity higher, so it might be infeasable. Backreferences raise the recognition power of the regex, and its difficulty is well
*positive look-ahead: is just another name for intersection, which raises the complexity of the aforementioned algorithm to O(m^2+n)
*negative look-ahead: a disaster for constructing the automaton (O(2^m), possibly PSPACE-complete). But should still be possible to tackle with the dynamic algorithm in something like O(n^2*m)
Note that with a concrete implementation, things might get better or worse. As a rule of thumb, simple features should be fast enough, and unambiguous (eg. not like a*a*) regexes are better.
A: To delve into theprise's answer, for the construction of the automaton, O(2^m) is the worst case, though it really depends on the form of the regular expression (for a very simple one that matches a word, it's in O(m), using for example the Knuth-Morris-Pratt algorithm).
A: From a purely theoretical stance:
The implementation I am familiar with would be to build a Deterministic Finite Automaton to recognize the regex. This is done in O(2^m), m being the size of the regex, using a standard algorithm. Once this is built, running a string through it is linear in the length of the string - O(n), n being string length. A replacement on a match found in the string should be constant time.
So overall, I suppose O(2^m + n).
A: Depends on the implementation. What language/library/class? There may be a best case, but it would be very specific to the number of features in the implementation.
A: You can trade space for speed by building a nondeterministic finite automaton instead of a DFA. This can be traversed in linear time. Of course, in the worst case this could need O(2^m) space. I'd expect the tradeoff to be worth it.
A: If you're after matching and substitution, that implies grouping and backreferences.
Here is a perl example where grouping and backreferences can be used to solve an NP complete problem:
http://perl.plover.com/NPC/NPC-3SAT.html
This (coupled with a few other theoretical tidbits) means that using regular expressions for matching and substitution is NP-complete.
Note that this is different from the formal definition of a regular expression - which don't have the notion of grouping - and match in polynomial time as described by the other answers.
A: In python's re library, even if a regex is compiled, the complexity can still be exponential (in string length) in some cases, as it is not built on DFA. Some references here, here or here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP? I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns.
So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:
public class CreateMemberPresenter
{
private ICreateMemberView view;
private IMemberTasks tasks;
public CreateMemberPresenter(ICreateMemberView view)
: this(view, new StubMemberTasks())
{
}
public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks)
{
this.view = view;
this.tasks = tasks;
HookupEventHandlersTo(view);
}
private void HookupEventHandlersTo(ICreateMemberView view)
{
view.CreateMember += delegate { CreateMember(); };
}
private void CreateMember()
{
if (!view.IsValid)
return;
try
{
int newUserId;
tasks.CreateMember(view.NewMember, out newUserId);
view.NewUserCode = newUserId;
view.Notify(new NotificationDTO() { Type = NotificationType.Success });
}
catch(Exception e)
{
this.LogA().Message(string.Format("Error Creating User: {0}", e.Message));
view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" });
}
}
}
I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.
Let's say the following Service Layer messages can show up:
*
*E-mail account already exists (failure)
*Refering user entered does not exist (failure)
*Password length exceeds datastore allowed length (failure)
*Member created successfully (success)
Let's also say that more rules will be in the service layer that the UI cannot anticipate.
Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.
Edit not by OP: merging in follow-up comments that were posted as answers by the OP
Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.
tgmdbm, I like the clever use of the lambda expression there!
Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.
However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?
Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:
For this kind of error, it's nice to report it to the same view.
Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.
A: As Cheekysoft suggests, I would tend to move all major exceptions into an ExceptionHandler and let those exceptions bubble up. The ExceptionHandler would render the appropriate view for the type of exception.
Any validation exceptions however should be handled in the view but typically this logic is common to many parts of your application. So I like to have a helper like this
public static class Try {
public static List<string> This( Action action ) {
var errors = new List<string>();
try {
action();
}
catch ( SpecificException e ) {
errors.Add( "Something went 'orribly wrong" );
}
catch ( ... )
// ...
return errors;
}
}
Then when calling your service just do the following
var errors = Try.This( () => {
// call your service here
tasks.CreateMember( ... );
} );
Then in errors is empty, you're good to go.
You can take this further and extend it with custome exception handlers which handle uncommon exceptions.
A: That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem.
Don't catch Exception
However, don't catch Exception in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions.
Plan a Simple Exception Hierarchy
If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes.
At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException.
Your presenter then has the option of doing
try {
// call service etc.
// handle success to view
}
catch (AccountAlreadyExistsException) {
// set the message and some other unique data in the view
}
catch (ServiceLayerException) {
// set the message in the view
}
// system exceptions, and unrecoverable exceptions are allowed to bubble
// up the call stack so a general error can be shown to the user, rather
// than showing the form again.
Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view.
I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.
A: In reply to the follow-up question:
As for creating exceptions becoming tedious, you kinda get used to it. Use of a good code generator or template can create the exception class with minimal hand editing within about 5 or 10 seconds.
However, in many real world applications, error handling can be 70% of the work, so it's all just part of the game really.
As tgmdbm suggests, in MVC/MVP applications I let all my unhandlable exceptions bubble up to the top and get caught by the dispatcher which delegates to an ExceptionHandler. I set it up so that it uses an ExceptionResolver that looks in the config file to choose an appropriate view to show the user. Java's Spring MVC library does this very well. Here's a snippet from a config file for Spring MVC's Exception resolver - its for Java/Spring but you'll get the idea.
This takes a huge amount of exception handling out of your presenters/controllers altogether.
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="UserNotFoundException">
rescues/UserNotFound
</prop>
<prop key="HibernateJdbcException">
rescues/databaseProblem
</prop>
<prop key="java.net.ConnectException">
rescues/networkTimeout
</prop>
<prop key="ValidationException">
rescues/validationError
</prop>
<prop key="EnvironmentNotConfiguredException">
rescues/environmentNotConfigured
</prop>
<prop key="MessageRejectedPleaseRetryException">
rescues/messageRejected
</prop>
</props>
</property>
<property name="defaultErrorView" value="rescues/general" />
</bean>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: What are the rules for naming AS3 classes? I'm trying to write a RegEx for a code generator (in C#) to determine a proper class or package name of an AS3 class.
I know that class names
*
*must start with a letter (capital or otherwise)
*any other digit can be alphanumeric
*cannot have spaces
Is there anything else?
A: Although you can start class names with lower case letters and include underscores and dollar signs, the "naming convention" is to start the class name and each separate word with a capital letter (e.g. UsefulThing), and not include underscores. When I see classes like useful_thing, it looks wrong, because it's not the naming convention. Maybe your question should have said what are the valid names for an AS3 class?
Other than that I think you + maclema have it.
A: The conventions for Class and Package naming as far as I've heard:
The package structure should use the "flipped domain" naming, with lowercase folders and CamelCased class names, i.e.:
import com.yourdomain.nameofsubfolder.YourSpecialClass;
This is reflected in all of the packages shipped with Flash and Flex. Examples:
import flash.events.MouseEvent;
import flash.display.MovieClip;
There is also a convention of naming Interfaces after the functionality they add or impose as in: Styleable, Drawable, Movable etc... Many (including Adobe) also prefer to use an upper case "I" to mark interfaces clearly as such, i.e.:
IEventDispatcher
IExternalizable
IFocusManager
which are all internal interfaces in the flash.* packages.
A: Here are some more valid classes.
Actionscript 3 classes (and packages) must start with a letter, "_", or "$". They may also contain (but not start with) a number.
public class $Test {}
public class _Test {}
public class test {}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: List or BusinessObjectCollection? Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable
IE:
public class CollectionBase : IEnumerable
and then would derive their Business Object collections from that.
public class BusinessObjectCollection : CollectionBase
Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:
public class BusinessObjectCollection : List<BusinessObject>
I do this because I like to have strongly typed names instead of just passing Lists around.
What is your approach?
A: I prefer just to use List<BusinessObject>. Typedefing it just adds unnecessary boilerplate to the code. List<BusinessObject> is a specific type, it's not just any List object, so it's still strongly typed.
More importantly, declaring something List<BusinessObject> makes it easier for everyone reading the code to tell what types they are dealing with, they don't have to search through to figure out what a BusinessObjectCollection is and then remember that it's just a list. By typedefing, you'll have to require a consistent (re)naming convention that everyone has to follow in order for it to make sense.
A: I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time.
However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes.
Basically, C# 3.0 allows any class that implements IEnumerable and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax:
var d = new Dictionary<string, int>
{
{"hello", 0},
{"the answer to life the universe and everything is:", 42}
};
The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection:
class c1 : IEnumerable
{
void Add(int x1, int x2, int x3)
{
//...
}
//...
}
it would be possible to initialize it like so:
var x = new c1
{
{1,2,3},
{4,5,6}
}
This can be really useful if you need to create static tables of complex objects. For example, if you were just using List<Customer> and you wanted to create a static list of customer objects you would have to create it like so:
var x = new List<Customer>
{
new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"),
new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"),
new Customer("Michael Scott", "555-555-8769", "Scranton PA"),
new Customer("Ali G", "", "Staines", "UK")
}
However, if you use a customized collection, like this one:
class CustomerList : List<Customer>
{
public void Add(string name, string phoneNumber, string city, string stateOrCountry)
{
Add(new Customer(name, phoneNumber, city, stateOrCounter));
}
}
You could then initialize the collection using this syntax:
var customers = new CustomerList
{
{"Scott Wisniewski", "555-555-5555", "Seattle", "WA"},
{"John Doe", "555-555-1234", "Los Angeles", "CA"},
{"Michael Scott", "555-555-8769", "Scranton PA"},
{"Ali G", "", "Staines", "UK"}
}
This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex.
That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database.
My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use List<T> directly.
A: I've been going back and forth on 2 options:
public class BusinessObjectCollection : List<BusinessObject> {}
or methods that just do the following:
public IEnumerable<BusinessObject> GetBusinessObjects();
The benefits of the first approach is that you can change the underlying data store without having to mess with method signatures. Unfortunately if you inherit from a collection type that removes a method from the previous implementation, then you'll have to deal with those situations throughout your code.
A: Use the type List<BusinessObject> where you have to declare a list of them. However,
where you return a list of BusinessObject, consider returning IEnumerable<T>, IList<T> or ReadOnlyCollection<T> - i.e. return the weakest possible contract that satisfies the client.
Where you want to "add custom code" to a list, code extension methods on the list type. Again, attach these methods to the weakest possible contract, e.g.
public static int SomeCount(this IEnumerable<BusinessObject> someList)
Of course, you can't and shouldn't add state with extension methods, so if you need to add a new property and a field behind it, use a subclass or better, a wrapper class to store this.
A: You should probably avoid creating your own collection for that purpose. It's pretty common to want to change the type of data structure a few times during refactorings or when adding new features. With your approach, you would wind up with a separate class for BusinessObjectList, BusinessObjectDictionary, BusinessObjectTree, etc.
I don't really see any value in creating this class just because the classname is more readable. Yeah, the angle bracket syntax is kind of ugly, but it's standard in C++, C# and Java, so even if you don't write code that uses it you're going to run into it all the time.
A: I generally only derive my own collection classes if I need to "add value". Like, if the collection itself needed to have some "metadata" properties tagging along with it.
A: I do the exact same thing as you Jonathan... just inherit from List<T>. You get the best of both worlds. But I generally only do it when there is some value to add, like adding a LoadAll() method or whatever.
A: You can use both. For laziness - I mean productivity - List is a very useful class, it's also "comprehensive" and frankly full of YANGNI members. Coupled with the sensible argument / recommendation put forward by the MSDN article already linked about exposing List as a public member, I prefer the "third" way:
Personally I use the decorator pattern to expose only what I need from List i.e:
public OrderItemCollection : IEnumerable<OrderItem>
{
private readonly List<OrderItem> _orderItems = new List<OrderItem>();
void Add(OrderItem item)
{
_orderItems.Add(item)
}
//implement only the list members, which are required from your domain.
//ie. sum items, calculate weight etc...
private IEnumerator<string> Enumerator() {
return _orderItems.GetEnumerator();
}
public IEnumerator<string> GetEnumerator() {
return Enumerator();
}
}
Further still I'd probably abstract OrderItemCollection into IOrderItemCollection so I can swap my implementation of IOrderItemCollection over in the future in (I may prefer to use a different inner enumerable object such as Collection or more likley for perf use a Key Value Pair collection or Set.
A: It's recommended that in public API's not to use List<T>, but to use Collection<T>
If you are inheriting from it though, you should be fine, afaik.
A: I use generic lists for almost all scenarios. The only time that I would consider using a derived collection anymore is if I add collection specific members. However, the advent of LINQ has lessened the need for even that.
A: 6 of 1, half dozen of another
Either way its the same thing. I only do it when I have reason to add custom code into the BusinessObjectCollection.
With out it having load methods return a list allows me to write more code in a common generic class and have it just work. Such as a Load method.
A: As someone else pointed out, it is recommended not to expose List publicly, and FxCop will whinge if you do so. This includes inheriting from List as in:
public MyTypeCollection : List<MyType>
In most cases public APIs will expose IList (or ICollection or IEnumerable) as appropriate.
In cases where you want your own custom collection, you can keep FxCop quiet by inheriting from Collection instead of List.
A: If you choose to create your own collection class you should check out the types in System.Collections.ObjectModel Namespace.
The namespace defines base classes thare are ment to make it easier for implementers to create a custom collections.
A: I tend to do it with my own collection if I want to shield the access to the actual list. When you are writing business objects, chance is that you need a hook to know if your object is being added/removed, in such sense I think BOCollection is better idea. Of coz if that is not required, List is more lightweight. Also you might want to check using IList to provide additional abstraction interface if you need some kind of proxying (e.g. a fake collection triggers lazy load from database)
But... why not consider Castle ActiveRecord or any other mature ORM framework? :)
A: At the most of the time I simply go with the List way, as it gives me all the functionality I need at the 90% of the time, and when something 'extra' is needed, I inherit from it, and code that extra bit.
A: I would do this:
using BusinessObjectCollection = List<BusinessObject>;
This just creates an alias rather than a completely new type. I prefer it to using List<BusinessObject> directly because it leaves me free to change the underlying structure of the collection at some point in the future without changing code that uses it (as long as I provide the same properties and methods).
A: try out this:
System.Collections.ObjectModel.Collection<BusinessObject>
it makes unnecessary to implement basic method like CollectionBase do
A: this is the way:
return arrays, accept IEnumerable<T>
=)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Favorite (G)Vim plugins/scripts? What are your favorite (G)Vim plugins/scripts?
A: Nerdtree
The NERD tree allows you to explore your filesystem and to open files and
directories. It presents the filesystem to you in the form of a tree which you
manipulate with the keyboard and/or mouse. It also allows you to perform
simple filesystem operations.
The tree can be toggled easily with :NERDTreeToggle which can be mapped to a more suitable key. The keyboard shortcuts in the NERD tree are also easy and intuitive.
Edit: Added synopsis
A: Tomas Restrepo posted on some great Vim scripts/plugins. He has also pointed out some nice color themes on his blog, too. Check out his Vim category.
A: No one said matchit yet ? Makes HTML / XML soup much nicer
http://www.vim.org/scripts/script.php?script_id=39
A: With version 7.3, undo branches was added to vim. A very powerful feature, but hard to use, until Steve Losh made Gundo which makes this feature possible to use with a ascii
representation of the tree and a diff of the change. A must for using undo branches.
A: Matrix Mode.
A: My latest favourite is Command-T. Granted, to install it you need to have Ruby support and you'll need to compile a C extension for Vim. But oy-yoy-yoy does this plugin make a difference in opening files in Vim!
A: Conque Shell : Run interactive commands inside a Vim buffer
Conque is a Vim plugin which allows you to run interactive programs, such as bash on linux or powershell.exe on Windows, inside a Vim buffer. In other words it is a terminal emulator which uses a Vim buffer to display the program output.
http://code.google.com/p/conque/
http://www.vim.org/scripts/script.php?script_id=2771
A: Tim Pope has some kickass plugins. I love his surround plugin.
A: The vcscommand plugin provides global ex commands for manipulating version-controlled source files and it supports CVS,SVN and some other repositories.
You can do almost all repository related tasks from with in vim:
* Taking the diff of current buffer with repository copy
* Adding new files
* Reverting the current buffer to the repository copy by nullifying the local changes....
A: Just gonna name a few I didn't see here, but which I still find extremely helpful:
*
*Gist plugin - Github Gists (Kind
of Githubs answer to Pastebin,
integrated with Git for awesomeness!)
*Mustang color scheme (Can't link directly due to low reputation, Google it!) - Dark, and beautiful color scheme. Looks really good in the terminal, and even better in gVim! (Due to 256 color support)
A: One Plugin that is missing in the answers is NERDCommenter, which let's you do almost anything with comments. For example {add, toggle, remove} comments. And more. See this blog entry for some examples.
A: Pathogen plugin and more things commented by Steve Losh
A: I like taglist and fuzzyfinder, those are very cool plugin
A: TaskList
This script is based on the eclipse Task List. It will search the file for FIXME, TODO, and XXX (or a custom list) and put them in a handy list for you to browse which at the same time will update the location in the document so you can see exactly where the tag is located. Something like an interactive 'cw'
A: I really love the snippetsEmu Plugin. It emulates some of the behaviour of Snippets from the OS X editor TextMate, in particular the variable bouncing and replacement behaviour.
A: Zenburn color scheme and good fonts - [Droid Sans Mono](http://en.wikipedia.org/wiki/Droid_(font)) on Linux, Consolas on Windows.
A: If you're on a Mac, you got to use peepopen, fuzzyfinder on steroids.
A: Taglist, a source code browser plugin for Vim, is currently the top rated plugin at the Vim website and is my favorite plugin.
A: I love snipMate. It's simular to snippetsEmu, but has a much better syntax to read (like Textmate).
A: A very nice grep replacement for GVim is Ack. A search plugin written in Perl that beats Vim's internal grep implementation and externally invoked greps, too. It also by default skips any CVS directories in the project directory, e.g. '.svn'. This blog shows a way to integrate Ack with vim.
A: A.vim is a great little plugin. It allows you to quickly switch between header and source files with a single command. The default is :A, but I remapped it to F2 reduce keystrokes.
A: I use the following two plugins all the time:
*
*project
*vimoutliner
A: For vim I like a little help with completions. Vim has tons of completion modes, but really, I just want vim to complete anything it can, whenver it can.
I hate typing ending quotes, but fortunately this plugin obviates the need for such misery.
Those two are my heavy hitters.
This one may step up to roam my code like an unquiet shade, but I've yet to try it.
A: Txtfmt (The Vim Highlighter)
Screenshots
The Txtfmt plugin gives you a sort of "rich text" highlighting capability, similar to what is provided by RTF editors and word processors. You can use it to add colors (foreground and background) and formatting attributes (all combinations of bold, underline, italic, etc...) to your plain text documents in Vim.
The advantage of this plugin over something like Latex is that with Txtfmt, your highlighting changes are visible "in real time", and as with a word processor, the highlighting is WYSIWYG. Txtfmt embeds special tokens directly in the file to accomplish the highlighting, so the highlighting is unaffected when you move the file around, even from one computer to another. The special tokens are hidden by the syntax; each appears as a single space. For those who have applied Vince Negri's conceal/ownsyntax patch, the tokens can even be made "zero-width".
A: tcomment
"I map the "Command + /" keys so i can just comment stuff out while in insert mode
imap :i
A: I really like the SuperTab plugin, it allows you to use the tab key to do all your insert completions.
A: I have recently started using a plugin that highlights differences in your buffer from a previous version in your RCS system (Subversion, git, whatever). You just need to press a key to toggle the diff display on/off. You can find it here: http://github.com/ghewgill/vim-scmdiff. Patches welcome!
A: *
*Elegant (mini) buffer explorer - This is the multiple file/buffer manager I use. Takes very little screen space. It looks just like most IDEs where you have a top tab-bar with the files you've opened. I've tested some other similar plugins before, and this is my pick.
*TagList - Small file explorer, without the "extra" stuff the other file explorers have. Just lets you browse directories and open files with the "enter" key. Note that this has already been noted by previous commenters to your questions.
*SuperTab - Already noted by WMR in this post, looks very promising. It's an auto-completion replacement key for Ctrl-P.
*Desert256 color Scheme - Readable, dark one.
*Moria color scheme - Another good, dark one. Note that it's gVim only.
*Enahcned Python syntax - If you're using Python, this is an enhanced syntax version. Works better than the original. I'm not sure, but this might be already included in the newest version. Nonetheless, it's worth adding to your syntax folder if you need it.
*Enhanced JavaScript syntax - Same like the above.
*EDIT: Comments - Great little plugin to [un]comment chunks of text. Language recognition included ("#", "/", "/* .. */", etc.) .
A: Not a plugin, but I advise any Mac user to switch to the MacVim distribution which is vastly superior to the official port.
As for plugins, I used VIM-LaTeX for my thesis and was very satisfied with the usability boost. I also like the Taglist plugin which makes use of the ctags library.
A: clang complete - the best c++ code completion I have seen so far. By using an actual compiler (that would be clang) the plugin is able to complete complex expressions including STL and smart pointers.
A: I take buftabs.vim and localvimrc.vim with me whereever I go!
buftabs : Minimalistic buffer tabs saving screen space
Local configuration : Use different settings for different directories.
A: Try trinity
It has :
1) NerdTree
2) SourceExplorer
3) TagList
A: Mark
*
*It supports Multiple Highliting.
A: xptemplate
intelligent snippet management:
http://www.vimeo.com/7614329
A: During maintenance of a very big and old C++ project I've created two plugins and these are the only ones I use:
*
*SourceCodeObedience
*0scan
0scan substitute for me taglist, buflist, files explorers, and other things like quick convenience file search.
SourceCodeObedience is very convenient cscope and ctags code surfing with stored history of all your searches with 'Filter' feature.
I use them not because they are mine but because they do the complete job and helps me to maintain of ~1Gb unfamiliar code base.
A: neocomplcache, the it behave a few like scribes autocompletion.
A: vimtabs in gvim. Awesome and quick way to switch between buffers without wasting any space.
A: DirDiff
Vim's very own directory differ.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "165"
} |
Q: Problems running Swing application with IDEA 8M1 Is anyone else having trouble running Swing applications from IntelliJ IDEA 8 Milestone 1? Even the simplest application of showing an empty JFrame seems to crash the JVM. I don't get a stack trace or anything, it looks like the JVM itself crashes and Windows shows me a pop-up that says the usual "This process is no longer responding" message.
Console applications work fine, and my Swing code works fine when launching from Netbeans or from the command line. I'm running Windows Vista x64 with the JDK 1.6 Update 10 beta, which may be a configuration the Jetbrains guys haven't run into yet.
A: Ask your question directly on the IDEA website. They always react fast and the problem you have is probably either fixed or documented.
A: IDEA 8 Milestone 1 is a beta(ish) "based on a new platform". This may have changed the way that swing is handled. Also you are running a beta JDK.
You will probably get more help/submit a bug at the Jetbrain forums unless they are on SO also. Here is the bug tracker link
A: I have actually experienced problems from using the JDK 6u10 beta myself and had to downgrade to JDK 6u7 for the time being. This solved some of my problems with among other things swing.
Also, i have been running IJ8M1 since the 'release' and I am very satisfied with it, especially if you regard the "beta" tag. It feels snappier and also supports multiple cores which makes my development machine rejoice. ;p
Anyway, i use WinXP32 and IJ8M1 with JDK 6u7 and that is afaik very stable indeed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple form Delphi applications and dialogs I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window.
If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight.
I've tried setting the owner and the ParentWindow properties to the form it is related to:
dialog := TDialogForm.Create( parentForm );
dialog.ParentWindow := parentForm.Handle;
How can I fix this problem? What else should I be trying?
Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order.
Note: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.
A: I'd use this code... (Basically what Lars said)
dialog := TDialogForm.Create( parentForm );
dialog.PopupParent := parentForm;
dialog.PopupMode := pmExplicit;
dialog.ShowModal();
A: I ultimately ended up finding the answer using Google Groups. In a nutshell, all the modal dialogs need to have the following added to them:
procedure TDialogForm.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style or WS_POPUP;
Params.WndParent := (Owner as TWinControl).Handle;
end;
I'm guessing this does the equivalent of Lars' and Marius' answers in Delphi 7.
A: Is the dialog shown using ShowModal or just Show? You should probably set the PopupMode property correct of the your dialog. pmAuto would probably your best choice. Also see if you need to set the PopupParent property.
A: First of all, I am not completely sure I follow, you might need to provide some additional details to help us understand what is happening and what the problem is. I guess I am not sure I understand exactly what you're trying to accomplish and what the problem is.
Second, you shouldn't need to set the dialog's parent since that is essentially what is happening with the call to Create (passing the parent). The dialogs you're describing sound like they could use some "re-thinking" a bit to be honest. Is this dialog to enter the properties of the image a child of the source window, or the WYSIWYG window?
A: I'm not sure I quite understand what you are getting at, but here's a few things I can suggest you can try...
*
*This behaviour changes between different versions of Delphi. I'd suggest that this is due to the hoops they jumped through to support Windows Vista in Delphi 2007.
*If you are using Delphi 2007, try removing the line from the project source file that sets the Application.MainFormOnTaskBar boolean variable.
*With this removed, you should be able to use the various Form's BringToFront / SendToBack methods to achieve the Z-ordering that you are after.
I suspect that what you've discovered has been discussed on this link
Of course, I may have just missed your point entirely, so apologies in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to use BITS to download from a UNC path? What is the best way to distribute files to users in remote offices, using BITS with a UNC path or BITS with HTTP? I have a VB.NET project which currently downloads from a HTTP path, but there is added complexity involved (e.g. having a web server).
Or is there a better way to do this? Low bandwith usage is more important than speed of synching.
A: Maybe consider not using BITS at all and use the old favourite Robocopy. Robocopy is a standalone command-line executable which is part of the Windows Server 2003 ResKit tools and now standard on Vista/2008. Robocopy has the /IPG:ms (Inter-Packet Gap) switch to "dribble" the download, which is designed specifically to not saturate slow links.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open source rules engine with decent interface for writing rules I'm trying to locate an open source business rules engine that has a decent interface for building the rules.
OR at least one that works well on the .Net platform and has been updated sometime in the past 12 months.
Thanks,
A: NxBRE is one option.
http://sourceforge.net/projects/nxbre/#item3rd-5
A: .NET Application Block for Validation and Business Rules
A: You can use Reaction RuleML. The Rule Manager from Acumen Business has an adapter for business users to generate a valid RuleML document
A: I'm going to throw one more piece of software I ran across: ncalc.
It's not exactly a "rules" engine; but it does do dynamic calculations where you can give it the expression to evaluate and all of the variables necessary. This was pretty much exactly all I needed for the app I was working on.
For a simple engine it works just fine. As far as an interface, it wasn't that complicated to build a few pages to let people type in the expressions.
For more complicated things, NxBRE is a better option; as @Kevin Dente answered above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Why can't I declare static methods in an interface? The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?
public interface ITest {
public static String test();
}
The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
A: There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
public interface Foo {
public static int bar();
}
and
public interface Foo {
public static int bar() {
...
}
}
The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition.
Java could allow the latter; and in fact, starting in Java 8, it does!
A: Static methods are not instance methods. There's no instance context, therefore to implement it from the interface makes little sense.
A: Now Java8 allows us to define even Static Methods in Interface.
interface X {
static void foo() {
System.out.println("foo");
}
}
class Y implements X {
//...
}
public class Z {
public static void main(String[] args) {
X.foo();
// Y.foo(); // won't compile because foo() is a Static Method of X and not Y
}
}
Note: Methods in Interface are still public abstract by default if we don't explicitly use the keywords default/static to make them Default methods and Static methods resp.
A: The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.
A: There's a very nice and concise answer to your question here. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)
A: It seems the static method in the interface might be supported in Java 8, well, my solution is just define them in the inner class.
interface Foo {
// ...
class fn {
public static void func1(...) {
// ...
}
}
}
The same technique can also be used in annotations:
public @interface Foo {
String value();
class fn {
public static String getValue(Object obj) {
Foo foo = obj.getClass().getAnnotation(Foo.class);
return foo == null ? null : foo.value();
}
}
}
The inner class should always be accessed in the form of Interface.fn... instead of Class.fn..., then, you can get rid of ambiguous problem.
A: An interface is used for polymorphism, which applies to Objects, not types. Therefore (as already noted) it makes no sense to have an static interface member.
A: I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:
Math.add(2, 3);
If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.
A: The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:
public class A {
public method x() {...}
}
public class B {
public method x() {...}
}
public class C extends A, B { ... }
Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.
Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:
public interface A {
public static method x() {...}
}
public interface B {
public static method x() {...}
}
public class C implements A, B { ... }
Same problem here, what happen if you call C.x()?
A: Java 8 Had changed the world you can have static methods in interface but it forces you to provide implementation for that.
public interface StaticMethodInterface {
public static int testStaticMethod() {
return 0;
}
/**
* Illegal combination of modifiers for the interface method
* testStaticMethod; only one of abstract, default, or static permitted
*
* @param i
* @return
*/
// public static abstract int testStaticMethod(float i);
default int testNonStaticMethod() {
return 1;
}
/**
* Without implementation.
*
* @param i
* @return
*/
int testNonStaticMethod(float i);
}
A: Illegal combination of modifiers : static and abstract
If a member of a class is declared as static, it can be used with its class name which is confined to that class, without creating an object.
If a member of a class is declared as abstract, you need to declare the class as abstract and you need to provide the implementation of the abstract member in its inherited class (Sub-Class).
You need to provide an implementation to the abstract member of a class in sub-class where you are going to change the behaviour of static method, also declared as abstract which is a confined to the base class, which is not correct
A: Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .
A:
With Java 8, interfaces can now have static methods.
For example, Comparator has a static naturalOrder() method.
The requirement that interfaces cannot have implementations has also been relaxed. Interfaces can now declare "default" method implementations, which are like normal implementations with one exception: if you inherit both a default implementation from an interface and a normal implementation from a superclass, the superclass's implementation will always take priority.
A: Perhaps a code example would help, I'm going to use C#, but you should be able to follow along.
Lets pretend we have an interface called IPayable
public interface IPayable
{
public Pay(double amount);
}
Now, we have two concrete classes that implement this interface:
public class BusinessAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
public class CustomerAccount : IPayable
{
public void Pay(double amount)
{
//Logic
}
}
Now, lets pretend we have a collection of various accounts, to do this we will use a generic list of the type IPayable
List<IPayable> accountsToPay = new List<IPayable>();
accountsToPay.add(new CustomerAccount());
accountsToPay.add(new BusinessAccount());
Now, we want to pay $50.00 to all those accounts:
foreach (IPayable account in accountsToPay)
{
account.Pay(50.00);
}
So now you see how interfaces are incredibly useful.
They are used on instantiated objects only. Not on static classes.
If you had made pay static, when looping through the IPayable's in accountsToPay there would be no way to figure out if it should call pay on BusinessAcount or CustomerAccount.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "154"
} |
Q: PostgreSQL: GIN or GiST indexes? From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&&, @>, <@, etc). However I would be interested in advice about when to use one or the other (or neither possibly).
The PostgreSQL documentation has some information about this:
*
*GIN index lookups are about three times faster than GiST
*GIN indexes take about three times longer to build than GiST
*GIN indexes are about ten times slower to update than GiST
*GIN indexes are two-to-three times larger than GiST
However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms?
A: First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best.
Anyway, PostgreSQL documentation has a chapter on GIST and one on GIN, where you can find more info.
And, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
} |
Q: Switch branch names in git There may be more than one way to ask this question, so here's a desciption of the problem. 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. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch.
Some ways this could be asked/solved:
How do I rename my master branch to something else and then rename something else to master?
How do I back up master and then cause all commits I've backed up past to be on a different branch?
Thanks for all the (quick) answers! They're all good.
A: This is relatively easy:
git checkout -b fake_master master # fake_master now points to the same commit as master
git branch -D master # get rid of incorrect master
git checkout -b master real_master # master now points to your actual master
git checkout master # optional -- switch on to your master branch
A: I think you should consider a different development strategy to prevent issues like this. One that seems to work best for me is to never do development directly on my master branch. Regardless of the changes I'm making, I always create a new branch for new code:
git checkout -b topic/topic_name master
From there, I can push out the changes to public repositories:
git push pu topic/topic_name
or eventually just merge it back in with my master branch:
git checkout master && git merge topic/topic_name
If you truly need to go back to an older point in time and set that as your master, you can rename the current branch to something else and then check out an older version to be your master:
git branch -m master junk
git co -b master old_sha1_value
A: In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master:
git branch -m master crap_work
git branch -m previous_master master
A: Start on master, create a branch called in-progress, then reset master to an earlier commit.
$ git branch in-progress
$ git reset --hard HEAD^
A: This will set your master to any point in one step:
git checkout -B master new_point
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "107"
} |
Q: System.Web.Caching vs. Enterprise Library Caching Block For a .NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block.
*
*What do you use?
*Why?
System.Web.Caching
Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really.
*
*a KB article warning against 1.0 and 1.1 non web app use
*The 2.0 page has a comment that indicates it's OK: http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx
*Scott Hanselman is creeped out by the notion
*The 3.5 page includes a warning against such use
*Rob Howard encouraged use outside of web apps
I don't expect to use one of its highlights, SqlCacheDependency, but the addition of CacheItemUpdateCallback in .NET 3.5 seems like a Really Good Thing.
Enterprise Library Caching Application Block
*
*other blocks are already in use so the dependency already exists
*cache persistence isn't necessary; regenerating the cache on restart is OK
Some cache items should always be available, but be refreshed periodically. For these items, getting a callback after an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated.
Memcached for Win32 + .NET client
What are the pros and cons when you don't need a distributed cache?
A: Bear in mind that the EntLib documentation specifically steers you towards the ASP.NET cache for ASP.NET applications. That's probably the strongest recommendation towards using it here. Plus the EntLib cache doesn't have dependencies, which for me is a big reason not to use it.
I don't think there's a technical limitation as such on shipping System.Web as part of your app, though it's slightly odd that they've put that notice in on the .NET 3.5 page. Hanselman actually says he started out being creeped out by this notion, but became convinced. Also if you read the comments, he says that the block has too many moving parts and the ASP.NET Cache is much more lightweght.
I think this is exactly the kind of problem that Velocity is going to solve, but that's only a preview for now :-(
I'd say use Web.Caching and see how you get on. If you put some kind of abstraction layer over the top of it, you've always got the option to swap it out for the EntLib block later on if you find problems.
A: Take a look at memcached. It is a really cool, fast and lightweight distributed caching system. There are APIs for several of the most popular languages, including C#. It may not serve well on the client side (unless of course the client is obtaining the cached data from a server of some kind), but if you abstract your usage of memcached to a specific interface, you could then implement the interface with another caching system.
A: These are the items that I consider for the topic of Caching:
MemCached Win32
Velocity
.net Cache
Enterprise Library Caching Application Block
MemCached Win32: Up until recently I have used MemCached Win32. This is a akin to a web farm (many servers serving the same content for high availability) but it is a cache farm. This means that you can install it locally on your web server initially if you don't have the resources to go bigger. Then as you go down the road you can scale horizontally (more servers) or vertically (more hardware). This is a product that was ported from the original MemCached to work on Windows. This product has been used extensively in very high traffic sites. http://lineofthought.com/tools/memcached
Velocity: This is Microsofts answer to products such as MemCached. MemCached has been out for quite some time, Velocity is in CTP mode. I must say that from what I have read so far this product will certainly turn my head once it is out. But I can't bring myself to run big production projects on a CTP product with zero track record. I have started playing with it though as once it gains momentum MemCached won't even compare for those locked in the windows world! http://blogs.msdn.com/velocity/
.NET Cache: There is no reason to discount the standard .NET Cache. It is built in and ready to use for free and with no (major) set up required. It offers flexibility by way of offering mechanisms for storing items in local memory, a SINGLE state server, or a centralized database. Where Velocity steps in is when you need more than a single state server (cache in memory) and don't want to use a slow database for holding your cache.
Enterprise Application Block: I stay away from all of the Enterprise Application Blocks. They are heavy frameworks that give more than I generally require! As long as you remember to wrap everything that touches code that is not your own and follow simple rules for coding, stick to any of the other methods over this one! (just my opinion of course - MySpace leverages as much as they can out of Enterprise Application Blocks!)
You don't have to choose up front! I generally create a cache wrapper that I communicate with in my code for methods such as Get, Set, Exists, Remove, ListKeys, etc. This then points to an underlying level of cache abstraction that can point to MemCached, Velocity, or .NET cache. I use StructureMap (or choose another IoC container) to inject which form of cache I want to use for a given environment. In my local dev box I might use .NET cache in the session. In production I generally use MemCached Win 32. But regardless of how it is set up you can easily swap things around to try each system out to see what works best for you. You just need to make sure that you application knows as little as possible about how things are cached! Once this layer of abstraction is in place you can then do things such as run a compression algorithm (gzip) for all the data that is going in and out of cache which would allow you to store 10 times the amount of data in cache. - transparently.
I cover .NET Cache, MemCached Win32, StructureMap, and the appropriate abstractions in my book if you are interested!
ASP.NET 3.5 Social Networking (http://www.amazon.com/ASP-NET-3-5-Social-Networking-Enterprise-ready/dp/1847194788/ref=sr_1_1?ie=UTF8&s=books&qid=1225408005&sr=8-1 )
Andrew Siemer www.andrewsiemer.com blog.andrewsiemer.com www.socialnetworkingin.net
Update
Changed the link that lists sites using memcached. Thank you David for noticing that it was broken!
A: @Davide Vosti
"If they put it in the web namespace, I think's it's for a good reason."
Does that same logic apply to the Concurrency and Coordination Runtime (CCR) in the robotic studio? no? didn't think so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Dynamically Rendering asp:Image from BLOB entry in ASP.NET What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site.
I have done this by using
Response.Clear();
Response.ContentType = "image/pjpeg";
Response.BinaryWrite(imageConents);
Response.End();
but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?
A: You can BASE64 encode the content of the image directly into the SRC attribute, however, I believe only Firefox will parse this back into an image.
What I typically do is a create a very lightweight HTTPHandler to serve the images:
using System;
using System.Web;
namespace Example
{
public class GetImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString("id") != null)
{
Blob = GetBlobFromDataBase(id);
context.Response.Clear();
context.Response.ContentType = "image/pjpeg";
context.Response.BinaryWrite(Blob);
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You can reference this directly in your img tag:
<img src="GetImage.ashx?id=111"/>
Or, you could even create a server control that does it for you:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Example.WebControl
{
[ToolboxData("<{0}:DatabaseImage runat=server></{0}:DatabaseImage>")]
public class DatabaseImage : Control
{
public int DatabaseId
{
get
{
if (ViewState["DatabaseId" + this.ID] == null)
return 0;
else
return ViewState["DataBaseId"];
}
set
{
ViewState["DatabaseId" + this.ID] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<img src='getImage.ashx?id=" + this.DatabaseId + "'/>");
base.RenderContents(output);
}
}
}
This could be used like
<cc:DatabaseImage id="db1" DatabaseId="123" runat="server/>
And of course, you could set the databaseId in the codebehind as needed.
A: You don't want to be serving blobs from a database without implementing client side caching.
You will need to handle the following headers to support client side caching:
*
*ETag
*Expires
*Last-Modified
*If-Match
*If-None-Match
*If-Modified-Since
*If-Unmodified-Since
*Unless-Modified-Since
For an http handler that does this, check out:
http://code.google.com/p/talifun-web/wiki/StaticFileHandler
It has a nice helper to serve the content. It should be easy to pass in database stream to it. It also does server side caching which should help alleviate some of the pressure on the database.
If you ever decide to serve streaming content from the database, pdfs or large files the handler also supports 206 partial requests.
It also supports gzip and deflate compression.
These file types will benefit from further compression:
*
*css, js, htm, html, swf, xml, xslt, txt
*doc, xls, ppt
There are some file types that will not benefit from further compression:
*
*pdf (causes problems with certain versions in IE and it is usually well compressed)
*png, jpg, jpeg, gif, ico
*wav, mp3, m4a, aac (wav is often compressed)
*3gp, 3g2, asf, avi, dv, flv, mov, mp4, mpg, mpeg, wmv
*zip, rar, 7z, arj
A: Using ASP.Net with MVC this is pretty forward easy. You code a controller with a method like this:
public FileContentResult Image(int id)
{
//Get data from database. The Image BLOB is return like byte[]
SomeLogic ItemsDB= new SomeLogic("[ImageId]=" + id.ToString());
FileContentResult MyImage = null;
if (ItemsDB.Count > 0)
{
MyImage= new FileContentResult(ItemsDB.Image, "image/jpg");
}
return MyImage;
}
In your ASP.NET Web View or in this example, in your ASP.NET Web Form you can fill an Image Control with the URL to your method like this:
this.imgExample.ImageUrl = "~/Items/Image/" + MyItem.Id.ToString();
this.imgExample.Height = new Unit(120);
this.imgExample.Width = new Unit(120);
Voilá. Not HttpModules hassle was needed.
A: Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using(Image image = GetImage(context.Request.QueryString["ID"]))
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
Now just implement the GetImage method to load the image with the given ID, and you can use
<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" />
to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).
A: We actually just released some classes that help with exactly this kind of thing:
http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449
Specifically, check out the DatabaseImage sample.
A: Add the code to a handler to return the image bytes with the appropriate mime-type. Then you can just add the url to your handler like it is an image. For example:
<img src="myhandler.ashx?imageid=5">
Make sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Where can I find a "Math topic dependency tree" to assist my self-guided refresher on the subject? I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are here if you're interested in helping out).
My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??
What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?
Thank!
A: Here's how my school did it:
base:
algebra
trigonometry
analytic geometry
track 1 track 2 track 3
calc 1 linear algebra statistics
calc 2 discrete math 1
calc 3 (multivariable) discrete math 2
differential equations
The base courses were a prerequisite for everything, the tracks were independent and taken in order.
So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these:
algebra, discrete
algebra, linear algebra, discrete (if you want to cover matrices first)
HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck!
A: My advice is to lazily evaluate your own dependency tree. Study something you think is interesting -- when you hit something you don't know, go learn about it.
I always find it easier to learn something new when I already have a context in which I want to use it.
A: This is a particularly cool site for visualizing how everything in the math world fits together:
http://www.math.niu.edu/Papers/Rusin/known-math/index/mathmap.html
It's also got short summaries of many subfields you've probably never heard of, which is fun.
A: Usually, an overview of each field is a good thing to have when looking at any topic, but it's rare to have a genuine dependence the way we'd think of it. Algebra is always needed. I can't think of a time I've needed any trigonometry. (except to expand it with new things from calculus) I'm even quite sure people wouldn't agree on what a dependency graph would look like, or even in which field each topic belongs.
I think the right way to approach it is to just collect a wide range of topics from all of branches and read them in whatever order you feel like, recording dependencies between topics as you go. (respecting them, or not, as you please.) This should have the far more important property of keeping the student interested.
It's also my experience that if something just has you stumped, just mark it and set it aside for later.
As for my school, well, it was similar to Harrison's:
*
*cominatorics,
*linear algebra,
*calculus,
*numerical analysis (error analysis in particular.)
*logic,
*statistics, (with operations research / queueing therory.)
A: Take a look at MathWorld. Browse topics or search for one, you'll get your position in the overall tree.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: "Silent" Printing in a Web Application I'm working on a web application that needs to prints silently -- that is without user involvement. What's the best way to accomplish this? It doesn't like it can be done with strictly with Javascript, nor Flash and/or AIR. The closest I've seen involves a Java applet.
I can understand why it would a Bad Idea for just any website to be able to do this. This specific instance is for an internal application, and it's perfectly acceptable if the user needs to add the URL to a trusted site list, install an addon, etc.
A: Here are two code samples you can try:
1:
<script>
function Print() {
alert ("THUD.. another tree bites the dust!")
if (document.layers)
{
window.print();
}
else if (document.all)
{
WebBrowser1.ExecWB(6, 1);
//use 6, 1 to prompt the print dialog or 6, 6 to omit it
//some websites also indicate that 6,2 should be used to omit the box
WebBrowser1.outerHTML = "";
}
}
</script>
<object ID="WebBrowser1" WIDTH="0" HEIGHT="0"
CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">
</object>
2:
if (navigator.appName == "Microsoft Internet Explorer")
{
var PrintCommand = '<object ID="PrintCommandObject" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
document.body.insertAdjacentHTML('beforeEnd', PrintCommand);
PrintCommandObject.ExecWB(6, -1); PrintCommandObject.outerHTML = "";
}
else {
window.print();
}
You may need to add the site/page you are testing on to you local intranet zone.
A: We struggled with a similar problem. We needed to print checks to a check printer, labels to a label printer, and customer invoices to an invoice printer for retail store embrasse-moi. We have dummy computers, nooks, ipads, iphones with no printing capabilities. The printing an invoice feature was basically a silent print. A pdf was written to the server, and a shell script was used locally to retrieve it and print.
We used the following for a perfect solution with minimal libraries:
*
*use TCPDF in PHP to create PDF. Store the PDF on the server. Put it in a 'Print Queue' Folder. Kudos for TCPDF, a bit difficult to learn, but SICK SICK SICK. Note we are printing 80 labels per page using avery 5167 with a bar code with perfect accuracy. We have a labels, check, and invoice print queue. Different folders basically for different printers.
*Use the included shell script to connect to the server via FTP, download the PDF, delete the PDF off the server, send the PDF to the printer, and again, delete the PDF.
*Using a local computer attached to the printer, run the script in terminal. obviously modify your printers and paths.
*Because you always want this running, and because you use a MAC, create an 'app' using automator. Start automator, put the script in a 'run shell script' and save. Then stick that app in a login item. See the script below the shell script if you want to see the 'output' window on the MAC.
BAM - works sick.
Here is the shell script
#!/bin/bash
# Get a remote directory Folder
# List the contents every second
# Copy the files to a local folder
# delete the file from server
# send the file to a printer
# delete the file
# compliments of embrasse-moi.com
clear # clear terminal window
echo "##########################################"
echo "Embrasse-Moi's Remote Print Queue Script"
echo "##########################################"
#Local Print Queue Directory
COPY_TO_DIRECTORY=/volumes/DATA/test/
echo "Local Directory: $COPY_TO_DIRECTORY"
#Priter
PRINTER='Brother_MFC_7820N'
echo "Printer Name: $PRINTER"
#FTP Info
USER="user"
PASS="pass"
HOST="ftp.yourserver.com"
#remote path
COPY_REMOTE_DIRECTORY_FILES=/path
echo "Remote Print Queue Directory: $HOST$COPY_REMOTE_DIRECTORY_FILES"
echo 'Entering Repeating Loop'
while true; do
#make the copy to directory if not exist
echo "Making Directory If it Does Not Exist"
mkdir -p $COPY_TO_DIRECTORY
cd $COPY_TO_DIRECTORY
######################### WGET ATTEMPTS ############################################
#NOTE wget will need to be installed
echo "NOT Using wget to retrieve remote files..."
# wget --tries=45 -o log --ftp-user=$USER --ftp-password=$PASS ftp://ftp.yourserver.com$COPY_REMOTE_DIRECTORY_FILES/*.pdf
######################### FTP ATTEMPTS ############################################
echo "NOT Using ftp to retrieve and delete remote files..."
#This seems to fail at mget, plus not sure how to delete file or loop through files
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASS
cd $COPY_REMOTE_DIRECTORY_FILES
ls
prompt
mget *
mdel *
END_SCRIPT
echo "Examining Files in $COPY_TO_DIRECTORY"
for f in $COPY_TO_DIRECTORY/*.pdf
do
# take action on each file. $f store current file name
#print
echo "Printing File: $f To: $PRINTER"
lpr -P $PRINTER $f
# This will remove the file.....
echo "Deleting File: $f"
rm "$f"
done
echo "Script Complete... now repeat until killed..."
sleep 5
done
and the automator script if you want to see output, keep the app with the script
choose a run apple script option:
on run {input, parameters}
tell application "Finder" to get folder of (path to me) as Unicode text
set workingDir to POSIX path of result
tell application "Terminal"
do script "sh " & "'" & workingDir & "script1.sh" & "'"
end tell
return input
end run
A: Here’s what you need to do to enable Firefox immediately print without showing the print preferences dialog box.
*
*Type about:config at Firefox’s location bar and hit Enter.
*Right click at anywhere on the page and select New > Boolean
*Enter the preference name as print.always_print_silent and click OK.
I found that somewhere and it helped me
A: I know this is an older thread, but it's still the top Google search for 'silent printing' so I'll add my findings for the benefit of anyone coming across this now.
We had a similar issue with printing labels of various types to various printers for a stocksystem. It took some trial and error, but we got around it by having the system create a pdf of the labels, with printer name and page qty's encoded in the pdf. All you then have to do is:
IN IE, go to Internet Options >> Security >> Trusted Sites >> Sites
Clear 'Require server verification (https:) for all sites in this zone'
add "http://[yoururl]"
and the pdf will print out automatically.
When we originally set this up we were using Chrome as the default browser, but in September 2015, Chrome dropped the ability to run NPAPI plugins. This meant that you could no longer select the Adobe pdf plugin as the default pdf handler, and the built in pdf plugin does not handle silent printing :-(
It does still work in Internet Explorer (IE11 at time of writing) but I've not tried any other browsers.
HTH
Cheers,
Nige
A: I wrote a python tsr that polled the server every so often (it pulled its polling frequency from the server) and would print out to label printer. Was relatively nice.
Once written in python, I used py2exe on it, then inno setup compiler, then put on intranet and had user install it.
It was not great, but it worked. Users would launch it in the morning, and the program would receive the kill switch from the server at night.
A: As @Axel wrote, Firefox has the print.always_print_silent option.
For Chrome, use the --kiosk-printing option to skip the Print Preview dialog:
Edit the shortcut you use to start Chrome and add "--kiosk-printing" then restart Chrome.
Note: If it doesn't work it is most likely because you did not completely stop Chrome, logging out and back in will surely do the trick.
A: I have it working all day long using a simple JSP page and the Java PDF Renderer library (https://pdf-renderer.dev.java.net). This works because Java prints using the OS and not the browser. Supposedly "silent printing" is considered a browser vulnerability/exploit and was patched after IE 6 so good luck getting it to work via Javascript or Active X. Maybe its possible but I couldn't get it to work without Java.
A: I have to be honest, I am kinda thinking out loud here.. But could it not be done with an applet or some sort (be it Java or whatever) that is given trusted permissions (such as that within the Intranet zone) or something?
May be worth investigating what permissions can be given to each zone?
Following a Google, I think you definately have a challenge, so far most of the articles I have seen involve printing to printers connected to the server.
If its internal, would it be possible to route printing from the server to department/user printers or something?
A: If it is just an internal application, then you can avoid printing from the browser, and send a printout directly from the server to the nearest printer to the user.
A: I'm on the same issue here, this is what i learn so far.
A.: You need to setup an IPP PrintServer
You have multiple print server implementations you may try.
*
*Hardware IPP print server: like DLINK DPR-1020 or similar, some printer have this functionality builtin.
*Linux server with CUPPS : http://www.howtoforge.com/ipp_based_print_server_cups
*XP-Pro server with ISS: http://www.michaelphipps.com/ipp-print-server-windows-xp-solution
B.: You need to make your WebApp a client of this IPP Server so you pick-process-send every user's print request to the PrintServer.
PHP::PRINT::IPP is a php lib you may try (it's well tested on cups servers).
A: You should have a look at PrintNode. They provide a silent remote printing services for web applications. You install a piece of software on the desktop which syncs to their servers. You can then send printjobs using an json request and they are instantly printed out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: IntelliSense for XElement objects with XML schema Reading an article called "Increase LINQ Query Performance" in July's MSDN magazine, the author states that using an Imports in VB providing a path to schema in the current project will turn IntelliSense on for XElement. In the code provided, he uses statements like xelement.@name to retreive attributes values and so on.
I did not try this out myself in VB but I would like to use that in C#. This really looks like LINQ to XSD.
Is there any equivalent in C#? It seems that it is not possible to use a namespace inside C# code, there is no using equivalent to this Import statement.
A: This post claims to have a link to a video that shows how to use VB9's XML Literals in C#. However, it only really discusses them and from what I can gather, you cannot use them in C#. http://blogs.msdn.com/bethmassi/archive/2008/07/03/teched-panel-vb-xml-literals-for-c-developers.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why Java and Python garbage collection methods are different? Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.
But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.
Why does Java choose this strategy and what is the benefit from this?
Is this better than the Python approach?
A: I think the article "Java theory and practice: A brief history of garbage collection" from IBM should help explain some of the questions you have.
A: One big disadvantage of Java's tracing GC is that from time to time it will "stop the world" and freeze the application for a relatively long time to do a full GC. If the heap is big and the the object tree complex, it will freeze for a few seconds. Also each full GC visits the whole object tree over and over again, something that is probably quite inefficient. Another drawback of the way Java does GC is that you have to tell the jvm what heap size you want (if the default is not good enough); the JVM derives from that value several thresholds that will trigger the GC process when there is too much garbage stacking up in the heap.
I presume that this is actually the main cause of the jerky feeling of Android (based on Java), even on the most expensive cellphones, in comparison with the smoothness of iOS (based on ObjectiveC, and using RC).
I'd love to see a jvm option to enable RC memory management, and maybe keeping GC only to run as a last resort when there is no more memory left.
A: Garbage collection is faster (more time efficient) than reference counting, if you have enough memory. For example, a copying gc traverses the "live" objects and copies them to a new space, and can reclaim all the "dead" objects in one step by marking a whole memory region. This is very efficient, if you have enough memory. Generational collections use the knowledge that "most objects die young"; often only a few percent of objects have to be copied.
[This is also the reason why gc can be faster than malloc/free]
Reference counting is much more space efficient than garbage collection, since it reclaims memory the very moment it gets unreachable. This is nice when you want to attach finalizers to objects (e.g. to close a file once the File object gets unreachable). A reference counting system can work even when only a few percent of the memory is free. But the management cost of having to increment and decrement counters upon each pointer assignment cost a lot of time, and some kind of garbage collection is still needed to reclaim cycles.
So the trade-off is clear: if you have to work in a memory-constrained environment, or if you need precise finalizers, use reference counting. If you have enough memory and need the speed, use garbage collection.
A: There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically...
Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this.
Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...
A: Reference counting is particularly difficult to do efficiently in a multi-threaded environment. I don't know how you'd even start to do it without getting into hardware assisted transactions or similar (currently) unusual atomic instructions.
Reference counting is easy to implement. JVMs have had a lot of money sunk into competing implementations, so it shouldn't be surprising that they implement very good solutions to very difficult problems. However, it's becoming increasingly easy to target your favourite language at the JVM.
A: Actually reference counting and the strategies used by the Sun JVM are all different types of garbage collection algorithms.
There are two broad approaches for tracking down dead objects: tracing and reference counting. In tracing the GC starts from the "roots" - things like stack references, and traces all reachable (live) objects. Anything that can't be reached is considered dead. In reference counting each time a reference is modified the object's involved have their count updated. Any object whose reference count gets set to zero is considered dead.
With basically all GC implementations there are trade offs but tracing is usually good for high through put (i.e. fast) operation but has longer pause times (larger gaps where the UI or program may freeze up). Reference counting can operate in smaller chunks but will be slower overall. It may mean less freezes but poorer performance overall.
Additionally a reference counting GC requires a cycle detector to clean up any objects in a cycle that won't be caught by their reference count alone. Perl 5 didn't have a cycle detector in its GC implementation and could leak memory that was cyclic.
Research has also been done to get the best of both worlds (low pause times, high throughput):
http://cs.anu.edu.au/~Steve.Blackburn/pubs/papers/urc-oopsla-2003.pdf
A: The latest Sun Java VM actually have multiple GC algorithms which you can tweak. The Java VM specifications intentionally omitted specifying actual GC behaviour to allow different (and multiple) GC algorithms for different VMs.
For example, for all the people who dislike the "stop-the-world" approach of the default Sun Java VM GC behaviour, there are VM such as IBM's WebSphere Real Time which allows real-time application to run on Java.
Since the Java VM spec is publicly available, there is (theoretically) nothing stopping anyone from implementing a Java VM that uses CPython's GC algorithm.
A: Darren Thomas gives a good answer. However, one big difference between the Java and Python approaches is that with reference counting in the common case (no circular references) objects are cleaned up immediately rather than at some indeterminate later date.
For example, I can write sloppy, non-portable code in CPython such as
def parse_some_attrs(fname):
return open(fname).read().split("~~~")[2:4]
and the file descriptor for that file I opened will be cleaned up immediately because as soon as the reference to the open file goes away, the file is garbage collected and the file descriptor is freed. Of course, if I run Jython or IronPython or possibly PyPy, then the garbage collector won't necessarily run until much later; possibly I'll run out of file descriptors first and my program will crash.
So you SHOULD be writing code that looks like
def parse_some_attrs(fname):
with open(fname) as f:
return f.read().split("~~~")[2:4]
but sometimes people like to rely on reference counting to always free up their resources because it can sometimes make your code a little shorter.
I'd say that the best garbage collector is the one with the best performance, which currently seems to be the Java-style generational garbage collectors that can run in a separate thread and has all these crazy optimizations, etc. The differences to how you write your code should be negligible and ideally non-existent.
A: Late in the game, but I think one significant rationale for RC in python is its simplicity. See this email by Alex Martelli, for example.
(I could not find a link outside google cache, the email date from 13th october 2005 on python list).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
} |
Q: Is it really that bad to catch a general exception? Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
A: There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
A: Well, I don't see any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
In conclusion, you will catch both IOException and NullPointerException with a generic Exception, but the way your program should react is probably different.
A: Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
A: The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
A: The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
A: I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
A: There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
*
*The top of all threads (By default, exceptions will vanish without a trace!)
*Inside a main processing loop that you expect to never exit
*Inside a Loop processing a list of objects where one failure shouldn't stop others
*Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
*If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
A: Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
A: In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
A: Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
A: Unpopular opinion: Not really.
Catch all of the errors you can meaningfully recover from. Sometimes that's all of them.
In my experience, it matters more where the exception came from than which exception is actually thrown. If you keep your exceptions in tight quarters, you won't usually be swallowing anything that would otherwise be useful. Most of the information encoded in the type of an error is ancillary information, so you generally end up effectively catching all of them anyway (but you now have to look up the API docs to get the total set of possible Exceptions).
Keep in mind that some exceptions that should bubble up to the top in almost every case, such as Python's KeyboardInterrupt and SystemExit. Fortunately for Python, these are kept in a separate branch of the exception hierarchy, so you can let them bubble up by catching Exception. A well-designed exception hierarchy makes this type of thing really straightforward.
The main time catching general exceptions will cause serious problems is when dealing with resources that need to be cleaned up (perhaps in a finally clause), since a catch-all handler can easily miss that sort of thing. Fortunately this isn't really an issue for languages with defer, constructs like Python's with, or RAII in C++ and Rust.
A: I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
A: Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
A: Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
A: For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "75"
} |
Q: How do I compare two arrays of DataRow objects in PowerShell? I have two arrays of System.Data.DataRow objects which I want to compare.
The rows have two columns A and B. Column A is a key and I want to find out which rows have had their B column changed and which rows have been added or deleted.
How do I do this in PowerShell?
A: I wrote a script to do this a little while back. The script (Compare-QueryResults.ps1) is available here and you will also need my Run-SQLQuery script (available here) or you can replace that with a script or function of your own.
Basically, what the script does is take the results of each of your queries and break the datarows apart so that each field is its own object. It then uses Compare-Object to check for any differences between the data in those rows. It returns a comparison object that shows you all the differences between the data returned.
The results are an object, so you can save them to a variable and use Sort-Object or the Format-* cmdlets with them.
Good luck. If you have any problems with the scripts, let me know, I'd be happy to walk you through them. I've been using them for application testing, seeing what rows are being modified by different actions in a program.
A: To simply compare two System.Data.DataRow, you can do something like this:
foreach ($property in ($row1 | Get-Member -MemberType Property)) {
$pName = $property.Name
if ($row1.$pName -ne $row2.$pName) {
Write-Host "== $pName =="
$row1.$pName
$row2.$pName
}
}
A: Do you need two arrays of DataRows? the DataRow object has a RowState property which will give you what you require. See the MSDN Docs: http://msdn.microsoft.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Date/time conversion using time.mktime seems wrong >>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?
A: Short answer: Because of timezones.
The Epoch is in UTC.
For example, I'm on IST (Irish Standard Time) or UTC+1. time.mktime() is relative to my timezone, so on my system this refers to
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0
Because you got the result 1233378000, that would suggest that you're 5 hours behind me
>>> (1233378000 - 1233360000) / (60*60)
5
Have a look at the time.gmtime() function which works off UTC.
A: mktime(...)
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
local time... fancy that.
The time tuple:
The other representation is a tuple of 9 integers giving local time.
The tuple items are:
year (four digits, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
Incidentally, we seem to be 6 hours apart:
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233356400.0
>>> (1233378000.0 - 1233356400)/(60*60)
6.0
A: Phil's answer really solved it, but I'll elaborate a little more. Since the epoch is in UTC, if I want to compare other times to the epoch, I need to interpret them as UTC as well.
>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000
>>> 1233360000 / (60*60*24)
14275
By converting the time tuple to a timestamp treating is as UTC time, I get a number which is evenly divisible by the number of seconds in a day.
I can use this to convert a date to a days-from-the-epoch representation which is what I'm ultimately after.
A: Interesting. I don't know, but I did try this:
>>> now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1))
>>> tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1))
>>> tomorrow - now
86400.0
which is what you expected. My guess? Maybe some time correction was done since the epoch. This could be only a few seconds, something like a leap year. I think I heard something like this before, but can't remember exactly how and when it is done...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Programmatically encrypting a config-file in .NET Could somebody please do a rundown of how to programmatically encrypt a config-file in .NET, preferably in C#.
What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings.
Also if anyone could list the types of encryption-providers and what is the difference between them.
I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET.
A: There is a good article from 4 guys about Encrypting Configuration Information in ASP.NET 2.0 Applications
Hope this helps
A: The solution at below site working fine for me.
http://www.a2zmenu.com/Blogs/CSharp/How-to-encrypt-configuration-file.aspx
A: To summarize the answers and what I've found so far, here are some good links to answer this question:
*
*Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com
*How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI - MSDN
Please feel free to complement with other links, maybe some to WinForms- or WPF-applications.
A: @TK: a hashing algo can only be 'guessed', not reverse engineered. One can only reconstruct the input to a hash value by completely guessing the input (apart from collisions, that is) This can be done by a rainbow crack for example (see an implementation of a rainbow cracker here)
I would say that a 3rd party encryption tool is not safer than the .NET framework encryption algorithms, these libraries just help you doing your job faster
A: I haven't used it myself, but the Microsoft Enterprise library has good encryption support that will possibly suit your needs:
http://msdn.microsoft.com/en-us/library/cc309503.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: FlashWindowEx FLASHW_STOP still keeps taskbar colored I am developing an application that controls an Machine.
When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing.
There's one little annoyance using the FlashWindowEx function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing).
[Flags]
public enum FlashMode {
/// <summary>
/// Stop flashing. The system restores the window to its original state.
/// </summary>
FLASHW_STOP = 0,
/// <summary>
/// Flash the window caption.
/// </summary>
FLASHW_CAPTION = 1,
/// <summary>
/// Flash the taskbar button.
/// </summary>
FLASHW_TRAY = 2,
/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
FLASHW_ALL = 3,
/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
FLASHW_TIMER = 4,
/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
FLASHW_TIMERNOFG = 12
}
public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) {
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = (UInt32)fm;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return FlashWindowEx(ref fInfo);
}
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO {
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
In my case I use FLASHW_TRAY to start flashing and FLASHW_STOP to stop the flashing.
Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?
A: Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use FLASHW_STOP, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloured because the user still may not have looked down and discovered which window was trying to get her attention. Keeping the button coloured keeps that information available.
A: Here's an error:
fInfo.uCount = UInt32.MaxValue;
You should set fInfo.uCount to zero when calling with FLASHW_STOP parameter.
Otherwise when you try to call stop when taskbar button is active it will stay active.
You can check a note about undefined behavior here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348(v=vs.85).aspx
I know that's an old post but it can help other people to solve this problem fast.
A: If that's the expected functionality I think it's not so useful, at least there should be a reset.
I fixed it now just using the FLASHW_ALL | FLASHW_TIMERNOFG combination.
A: Just set uCount to 0 to stop the flashing.
A: fixed with uCount=0
if (flags = FLASHW_STOP) { .uCount = 0 } else { .uCount = 800 }
The misbehaviour is that if you are calling flashw_stop from a click/kb event from inside the Window itself, the taskbar button stay colored if a that moment was colored.
With that new logic line, done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: XmlHttpRequest return values I'm looking for (arguably) the correct way to return data from a XmlHttpRequest. Options I see are:
*
*Plain HTML. Let the request format the data and return it in a usable format.
Advantage: easy to consume by the calling page.Disadvantage: Very rigid, stuck with a fixed layout.
*XML. Let the request return XML, format it using XSLT on the calling page.Advantage: the requested service is easily consumed by other sources.Disadvantage: Is browser support for XSLT good enough?
*JSON. Let the request return JSON, consume it using javascript, render HTML accordingly.Advantage: easier to 'OO-ify' the javascript making the request. Disadvantage: Probably not as easy to use as the previous two options.
I've also thought about going for option one while abstracting the view logic in the called service in such a way that switching in and out different layouts would be trivial. Personally I think this option is the best out of three, for compatibility reasons.
While typing this, I got another insight. Would it be a good idea to allow all three response formats, based on a parameter added to the request?
A: If you're looking for a quick solution that should work with most available frameworks, I'd go for JSON. It's easy to start with and works.
If you're trying to build a larger application that you're going to extend (in terms of size or maybe your own API for 3rd party extensions) I'd go for XML. You could write a proxy to provide the information in JSON or HTML too, but having XML as the main source is definitly worth the time and effort while building the app.
Like @John Topley said: it depends.
A: I'd agree with John Topley - it depends on the application. There's a good article on quirksmode that discusses the advantages and disadvantages of each format that you might want to read: http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html
A: I think this sort of depends on the level of "ajaxyness" your app is going to have. If your front end is a "rich client", al'a gmail, I'd go with the JSON solution, as you'd have to solve the problem of having client side view generation anyway. If you're using ajax sparingly, to provide simple messages to the user, update a few fields now and then, etc, then I'd go with option 1, since most of your view logic is already on the server.
A: Different response format shouldn't be difficult to produce.
JSON works best for me, i like to keep OO in js, and don't know how to parse XML well :)
A: I think trying to use XmlHttpRequest will be a huge headache, unless its the type of headache you don't mind - to do it properly you're almost reinventing the wheel. Then again, people like to reinvent wheels in their spare time, just to say, "Hey, I did it". Not me...
I would get a framework like prototype or Extjs, that has alot of data loading functions built in for XML and JSON, plus you'll get more predictable results, as the frameworks have event handlers to make sure your XmlHttpRequest succeeded or failed. Plus you get support for all the various browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: WPF Anti aliasing workaround Anti aliasing cannot be turned off in WPF. But I want to remove the blurred look of WPF fonts when they are small.
One possibility would be to use a .net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though.
Anyone has a solution for this? Any drawbacks from it?
Thank you
A: Have you tried putting a WindowsFormsHost control on a WPF window/control? That will allow WPF to render a WinForms control.
UPDATE November 2012: This question and answer is 4 years old. Text rendering has since improved in WPF. Please don't put WinForms controls in WPF apps; that was a hackish way to fix font rendering. It's no longer needed.
A: Anti-Alias can be turned off starting WPF 4.0 with following option:
TextOptions.TextFormattingMode="Display"
A: SnapsToDevicePixels has absolutely no effect on text rendering.
A: Microsoft have a blog dedicated to text rendering in WPF here WPF Text Blog
Things have definitely improved in .NET 4.0.
A: Offset the objects you draw, that you don't want to be antialiased, by 0.5px. This will cause the drawing engine to draw on the actual pixels, rather than drawing on the edge of the pixels (which is the default). When drawing on the edge of a pixel antialiasing normally occurs on the surrounding pixels.
This is similar to Quarts drawing on Mac.
Edit: Sorry, I didn't read the question. This doesn't work for fonts, only for shapes. I will leave the comment here for reference, though.
A: Try using the UIElement.SnapsToDevicePixels property on the UI elements of your window. People tend to report it works best for graphics and lines, but I've noticed improvment in text rendering with it as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Table cells larger than they are meant to be I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me ;)
I have made the latest version live so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated.
In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question.
I have also uploaded an image of the issue.
A: You could also adjust the line height of the td element:
td {
line-height: 0
}
A: I think you need to use display: block on your images. When images are inline there's a little extra space for the line spacing.
A: I know this might sound bad, but you need to ensure there is no whitespace between then end of you <img> tag and the start of the end </td> tag.
i.e. The following will present the problem:
<td>
<img src="image.jpg"/>
</td>
And this will not:
<td><img src="image.jpg"/></td>
Hope that helps.
Edit: OK, that wasn't the solution at all. doh!
A: I haven't looked up the whole thing, but the problem lies somewhere in the style sheets.
If you copy out only the table part of it, it is displaying the map correctly.
If you remove the final </span> tag from this part, it is also working (however the page gets mixed):
<div class="inner"><span class="corners-top"><span></span></span>
<div class="content" style="font-size: 1.1em;">
<!-- Stackoverflow findy thingy -->
<table border="0" cellspacing="0" cellpadding="0">
So either try from the beginning with the css or try to remove one-by-one them, to see, which is causing the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.