qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
115,928
|
<p>I need to have a thread signal another if the user wishes to interrupt execution, however I'm unsure about how to implement the signaling/signal-checking mechanism. I wouldn't like to have a singleton in my project (like a global <code>bool</code>), but is there an alternative?</p>
<p>In <a href="https://stackoverflow.com/questions/34151/c-thread-question-setting-a-value-to-indicate-the-thread-has-finished">this thread</a> people suggest proper structures for that in C++, but I don't know about anything similar in .NET. Could somebody please shed some light?</p>
|
[
{
"answer_id": 115962,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 4,
"selected": true,
"text": "private volatile bool cancelling;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4850/"
] |
115,955
|
<p>I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing. </p>
<p>In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query?</p>
<pre><code>var family = from p in db.Parents
where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"])
join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId
join c in db.Children on pcl.ChildId equals c.ChildId
select new
{
Family = "Name: " + p.ParentName + "<br />" +
"Children: " + NAMESOFCHILDREN? + "<br />"
};
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 115965,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "int parentID = Convert.ToInt32(Request.QueryString[\"parentId\"]);\n\nList<string> result =\n db.Parents\n .Where(p => p.ParentId == parentID)\n //.Where(p => p.ParentChildLookup.Children.Any())\n //.ToList()\n .Select(p => \n \"Name: \" + p.ParentName + \"<br />\" + \n \"Children: \" + String.Join(\", \", p.ParentChildLookup.Children.Select(c => c.Name).ToArray() + \"<br />\"\n)).ToList();\n"
},
{
"answer_id": 116001,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "var family = from p in db.Parents \n where p.ParentId == Convert.ToInt32(Request.QueryString[\"parentId\"]) \n join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId \n select new { \n Family = \"Name: \" + p.ParentName + \"<br />\" + string.Join(\",\",(from c in db.Children where c.ChildId equals pcl.ChildId select c.ChildId.ToString()).ToArray());\n };\n"
},
{
"answer_id": 30127101,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 0,
"selected": false,
"text": "groupby var query = from c in north.Customers\n join o in north.Orders on c.CustomerID equals o.CustomerID\n select new { c, o };\n\n var query2 = from q in query\n group q.o by q.c into g\n select new { CompanyName = g.Key.CompanyName, \n orderCount = g.Count(), \n orders = string.Join(\",\", g.Select(o => o.OrderID)) }\n into result\n orderby result.orderCount descending\n select result;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] |
115,971
|
<p>I'm getting an error message when I try to build my project in eclipse:</p>
<p><code>The type weblogic.utils.expressions.ExpressionMap cannot be resolved. It is indirectly referenced
from required .class files</code></p>
<p>I've looked online for a solution and cannot find one (except for those sites that make you pay for help). Anyone have any idea of a way to find out how to go about solving this problem? Any help is appreciated, thanks!</p>
|
[
{
"answer_id": 116004,
"author": "Kevin",
"author_id": 8530,
"author_profile": "https://Stackoverflow.com/users/8530",
"pm_score": 6,
"selected": true,
"text": "path->configure Add Library->Server Runtime Windows->Preferences->Server->Installed runtimes"
},
{
"answer_id": 40440279,
"author": "vaquar khan",
"author_id": 4812170,
"author_profile": "https://Stackoverflow.com/users/4812170",
"pm_score": 1,
"selected": false,
"text": "Description Resource Path Location Type\nThe project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project SpringBatch Unknown Java Problem\n Spring-bean.jar is missing\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459442/"
] |
115,974
|
<p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
|
[
{
"answer_id": 116035,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 5,
"selected": true,
"text": "from os import fork, setsid, umask, dup2\nfrom sys import stdin, stdout, stderr\n\nif fork(): exit(0)\numask(0) \nsetsid() \nif fork(): exit(0)\n\nstdout.flush()\nstderr.flush()\nsi = file('/dev/null', 'r')\nso = file('/dev/null', 'a+')\nse = file('/dev/null', 'a+', 0)\ndup2(si.fileno(), stdin.fileno())\ndup2(so.fileno(), stdout.fileno())\ndup2(se.fileno(), stderr.fileno())\n from os import getpid\noutfile = open(pid_file, 'w')\noutfile.write('%i' % getpid())\noutfile.close()\n from os import setuid, setgid, chdir\nfrom pwd import getpwnam\nfrom grp import getgrnam\nsetuid(getpwnam('someuser').pw_uid)\nsetgid(getgrnam('somegroup').gr_gid)\nchdir('/') \n"
},
{
"answer_id": 116081,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 0,
"selected": false,
"text": "$ easy_install grizzled\n\n>>> from grizzled.os import daemonize\n>>> daemon.daemonize()\n"
},
{
"answer_id": 3606303,
"author": "edomaur",
"author_id": 14262,
"author_profile": "https://Stackoverflow.com/users/14262",
"pm_score": 2,
"selected": false,
"text": "$ easy_install turkmenbashi\nimport Turkmenbashi\n\nclass DebugDaemon (Turkmenbashi.Daemon):\n\n def config(self):\n self.debugging = True\n\n def go(self):\n self.debug('a debug message')\n self.info('an info message')\n self.warn('a warning message')\n self.error('an error message')\n self.critical('a critical message')\n\nif __name__==\"__main__\":\n d = DebugDaemon()\n d.config()\n d.setenv(30, '/var/run/daemon.pid', '/tmp', None)\n d.start(d.go)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14262/"
] |
115,977
|
<p>I would very much like to integrate <a href="http://www.logilab.org/857" rel="noreferrer">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/" rel="noreferrer">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
|
[
{
"answer_id": 116047,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": false,
"text": "pylint --ignored-classes=Tags\n --ignore-classes --ignored-classes=<members names>"
},
{
"answer_id": 118375,
"author": "AdamKG",
"author_id": 16361,
"author_profile": "https://Stackoverflow.com/users/16361",
"pm_score": 3,
"selected": false,
"text": "objects = models.Manager()"
},
{
"answer_id": 1416297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "pylint --generated-members=objects"
},
{
"answer_id": 4162971,
"author": "simon",
"author_id": 88411,
"author_profile": "https://Stackoverflow.com/users/88411",
"pm_score": 5,
"selected": false,
"text": "[TYPECHECK]\ngenerated-members=REQUEST,acl_users,aq_parent,objects,_meta,id\n [TYPECHECK]\ngenerated-members=REQUEST,acl_users,aq_parent,objects,_meta,id,[a-zA-Z]+_set\n import re\n for pattern in self.config.generated_members:\n if re.match(pattern, node.attrname):\n return\n"
},
{
"answer_id": 31000713,
"author": "Tal Weiss",
"author_id": 78234,
"author_profile": "https://Stackoverflow.com/users/78234",
"pm_score": 7,
"selected": false,
"text": "ignores generated-members pip install pylint-django\n --load-plugins pylint_django\n"
},
{
"answer_id": 47774655,
"author": "Thiago Falcao",
"author_id": 1532769,
"author_profile": "https://Stackoverflow.com/users/1532769",
"pm_score": 5,
"selected": false,
"text": "pip install pylint-django \"python.linting.pylintArgs\": [\n \"--load-plugins=pylint_django\"\n],\n"
},
{
"answer_id": 50857799,
"author": "Ganesh",
"author_id": 3021579,
"author_profile": "https://Stackoverflow.com/users/3021579",
"pm_score": 2,
"selected": false,
"text": "neovim & vim8 w0rp's ale w0rp's ale pylint pylint-django vimrc let g:ale_python_pylint_options = '--load-plugins pylint_django'\n"
},
{
"answer_id": 72914402,
"author": "sage",
"author_id": 527489,
"author_profile": "https://Stackoverflow.com/users/527489",
"pm_score": 0,
"selected": false,
"text": "timekeeping # run on the entire timekeeping app/package\nheroku local:run pylint --load-plugins pylint_django timekeeping\n\n# run on the module timekeeping/report.py\nheroku local:run pylint --load-plugins pylint_django timekeeping/report.py\n\n# With temporary command line disables\nheroku local:run pylint --disable=invalid-name,missing-function-docstring --load-plugins pylint_django timekeeping/report.py\n E5110: Django was not configured. timekeeping heroku local:run python manage.py shell -c 'from pylint import lint; lint.Run(args=[\"--load-plugins\", \"pylint_django\", \"timekeeping\"])'\n\n# With temporary command line disables, specific module\nheroku local:run python manage.py shell -c 'from pylint import lint; lint.Run(args=[\"--load-plugins\", \"pylint_django\", \"--disable=invalid-name,missing-function-docstring\", \"timekeeping/report.py\"])'\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
115,979
|
<p>I got this flash application where you can click a link while watching a video. It will open a new tab and pause the video. Now when you come back to the flash application it would be nice if the video would start playing again. Is there a way, an event or so to do this ?</p>
|
[
{
"answer_id": 116022,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 1,
"selected": false,
"text": "<html>\n <head></head>\n <body onFocus=\"alert('testing');\"></body>\n</html>\n"
},
{
"answer_id": 228688,
"author": "jpencola",
"author_id": 30660,
"author_profile": "https://Stackoverflow.com/users/30660",
"pm_score": 2,
"selected": false,
"text": "stage.addEventListener( Event.ACTIVATE, playMovie );\nstage.addEventListener( Event.DEACTIVATE, pauseMovie );\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
] |
115,983
|
<p>How do I add an empty directory (that contains no files) to a Git repository?</p>
|
[
{
"answer_id": 115992,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 10,
"selected": false,
"text": "git add <dir>"
},
{
"answer_id": 116252,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": ".gitignore"
},
{
"answer_id": 125729,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 4,
"selected": false,
"text": ".gitignore *"
},
{
"answer_id": 180917,
"author": "m104",
"author_id": 4039,
"author_profile": "https://Stackoverflow.com/users/4039",
"pm_score": 5,
"selected": false,
"text": "$ mkdir tmp\n$ touch tmp/.gitignore\n$ git add tmp\n$ echo '*' > tmp/.gitignore\n$ git commit -m 'Empty directory' tmp\n"
},
{
"answer_id": 932982,
"author": "Jamie Flournoy",
"author_id": 115218,
"author_profile": "https://Stackoverflow.com/users/115218",
"pm_score": 13,
"selected": true,
"text": ".gitignore # Ignore everything in this directory\n*\n# Except this file\n!.gitignore\n"
},
{
"answer_id": 5537012,
"author": "Mild Fuzz",
"author_id": 445126,
"author_profile": "https://Stackoverflow.com/users/445126",
"pm_score": 3,
"selected": false,
"text": "function check_page_custom_folder_structure () {\n if (!is_dir(TEMPLATEPATH.\"/page-customs\"))\n mkdir(TEMPLATEPATH.\"/page-customs\"); \n if (!is_dir(TEMPLATEPATH.\"/page-customs/css\"))\n mkdir(TEMPLATEPATH.\"/page-customs/css\");\n if (!is_dir(TEMPLATEPATH.\"/page-customs/js\"))\n mkdir(TEMPLATEPATH.\"/page-customs/js\");\n}\n"
},
{
"answer_id": 5717707,
"author": "Peter Hoeg",
"author_id": 15512,
"author_profile": "https://Stackoverflow.com/users/15512",
"pm_score": 3,
"selected": false,
"text": "ruby -e 'require \"fileutils\" ; Dir.glob([\"target_directory\",\"target_directory/**\"]).each { |f| FileUtils.touch(File.join(f, \".gitignore\")) if File.directory?(f) }'"
},
{
"answer_id": 5871742,
"author": "mjs",
"author_id": 11543,
"author_profile": "https://Stackoverflow.com/users/11543",
"pm_score": 7,
"selected": false,
"text": ".gitignore .gitignore find . -type d -empty -exec touch {}/.gitignore \\;\n"
},
{
"answer_id": 5913813,
"author": "Lesmana",
"author_id": 360899,
"author_profile": "https://Stackoverflow.com/users/360899",
"pm_score": 5,
"selected": false,
"text": ".gitignore .gitignore .gitkeep .gitkeep .gitignore ls cp dir/* find -empty gitkeep README .gitkeep README for file in dirname/* mkdir find -type d -empty\n .git find -name .git -prune -o -type d -empty -print\n .gitkeep find -type f -name .gitkeep\n find -type f -printf \"%h\\n\" | sort | uniq -c | sort -n\n"
},
{
"answer_id": 6487199,
"author": "user665190",
"author_id": 665190,
"author_profile": "https://Stackoverflow.com/users/665190",
"pm_score": 2,
"selected": false,
"text": "php create_readme.php\n <?php\n $path = realpath('.');\n $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);\n foreach($objects as $name => $object){\n if ( is_dir($name) && ! is_empty_folder($name) ){\n echo \"$name\\n\" ;\n exec(\"touch \".$name.\"/\".\"README\");\n }\n }\n\n function is_empty_folder($folder) {\n $files = opendir($folder);\n while ($file = readdir($files)) {\n if ($file != '.' && $file != '..')\n return true; // Not empty\n }\n }\n?>\n git commit -m \"message\"\ngit push\n"
},
{
"answer_id": 7905820,
"author": "Brent Bradburn",
"author_id": 86967,
"author_profile": "https://Stackoverflow.com/users/86967",
"pm_score": 4,
"selected": false,
"text": "mkdir --parents .generated/bin ## create a folder for storing generated binaries\nmv myprogram1 myprogram2 .generated/bin ## populate the directory as needed\n ln -sf .generated/bin bin\ngit add bin\n rm -rf .generated ## this should be in a \"clean\" script or in a makefile\n .generated\n"
},
{
"answer_id": 8418403,
"author": "Artur79",
"author_id": 268780,
"author_profile": "https://Stackoverflow.com/users/268780",
"pm_score": 10,
"selected": false,
"text": ".gitkeep git add"
},
{
"answer_id": 8944077,
"author": "ofavre",
"author_id": 508831,
"author_profile": "https://Stackoverflow.com/users/508831",
"pm_score": 5,
"selected": false,
"text": "$ mkdir path/to/empty-folder\n $ git update-index --index-info\n040000 tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 path/to/empty-folder\n cd git write-tree git submodule init|update git update-index 040000 tree 160000 commit"
},
{
"answer_id": 13012436,
"author": "Thomas E",
"author_id": 1208895,
"author_profile": "https://Stackoverflow.com/users/1208895",
"pm_score": 5,
"selected": false,
"text": "mkdir log && touch log/.gitkeep && git add log/.gitkeep\n echo log/dev.log >> .gitignore\n"
},
{
"answer_id": 20388370,
"author": "Cranio",
"author_id": 1403638,
"author_profile": "https://Stackoverflow.com/users/1403638",
"pm_score": 8,
"selected": false,
"text": "cache/ logs/ .gitignore README .gitignore .gitignore .gitkeep .gitignore .gitkeep .gitkeep"
},
{
"answer_id": 21422128,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 9,
"selected": false,
"text": "touch .placeholder\n .placeholder /etc/cron.d/.placeholder .git README.md"
},
{
"answer_id": 24351531,
"author": "Roman",
"author_id": 2139671,
"author_profile": "https://Stackoverflow.com/users/2139671",
"pm_score": 3,
"selected": false,
"text": ".htaccess # Ignore everything in this directory\n*\n# Except this file\n!.gitignore\n!.htaccess\n /log /tmp /cache"
},
{
"answer_id": 27635349,
"author": "Stanislav Bashkyrtsev",
"author_id": 886697,
"author_profile": "https://Stackoverflow.com/users/886697",
"pm_score": 3,
"selected": false,
"text": "git submodule add path_to_repo .submodules .submodules"
},
{
"answer_id": 29884569,
"author": "Zaz",
"author_id": 405550,
"author_profile": "https://Stackoverflow.com/users/405550",
"pm_score": 4,
"selected": false,
"text": ".gitkeep .keep . README"
},
{
"answer_id": 37450055,
"author": "Mike",
"author_id": 1301994,
"author_profile": "https://Stackoverflow.com/users/1301994",
"pm_score": 3,
"selected": false,
"text": "git git .gitignore *\n!.gitignore\n $ echo \"*\" > .gitignore && echo '!.gitignore' >> .gitignore && git add .gitignore\n #!/bin/bash\n\ndir=''\n\nif [ \"$1\" != \"\" ]; then\n dir=\"$1/\"\nfi\n\necho \"*\" > $dir.gitignore && \\\necho '!.gitignore' >> $dir.gitignore && \\\ngit add $dir.gitignore\n $ ignore_dir ./some/directory\n * .gitignore .gitignore !.gitignore\n .gitignore"
},
{
"answer_id": 37597601,
"author": "Trendfischer",
"author_id": 685551,
"author_profile": "https://Stackoverflow.com/users/685551",
"pm_score": 3,
"selected": false,
"text": ".gitignore .keep mkdir empty\n README ln -s .this.directory empty/.keep\n .gitignore echo \"/empty\" >> .gitignore\n git add -f empty/.keep\n find empty -type f\n $ php -r \"var_export(glob('empty/.*'));\"\narray (\n 0 => 'empty/.',\n 1 => 'empty/..',\n)\n README"
},
{
"answer_id": 38313879,
"author": "Rahul Sinha",
"author_id": 3389121,
"author_profile": "https://Stackoverflow.com/users/3389121",
"pm_score": 2,
"selected": false,
"text": "/app/some-folder-to-exclude\n/another-folder-to-exclude/*\n *\n!.gitignore\n"
},
{
"answer_id": 43917066,
"author": "ajmedway",
"author_id": 2429318,
"author_profile": "https://Stackoverflow.com/users/2429318",
"pm_score": 3,
"selected": false,
"text": "/app/data/**/*.*\n!/app/data/**/*.md *.md . /app/data/ .gitignore .gitignore"
},
{
"answer_id": 43987053,
"author": "Mig82",
"author_id": 4124574,
"author_profile": "https://Stackoverflow.com/users/4124574",
"pm_score": 4,
"selected": false,
"text": "find . -type d -empty -exec touch {}/.gitkeep \\;\n pip3 install gitkeep2\n .gitkeep .gitkeep $ gitkeep --help\nUsage: gitkeep [OPTIONS] PATH\n\n Add a .gitkeep file to a directory in order to push them into a Git repo\n even if they're empty.\n\n Read more about why this is necessary at: https://git.wiki.kernel.org/inde\n x.php/Git_FAQ#Can_I_add_empty_directories.3F\n\nOptions:\n -r, --recursive Add or remove the .gitkeep files recursively for all\n sub-directories in the specified path.\n -l, --let-go Remove the .gitkeep files from the specified path.\n -e, --empty Create empty .gitkeep files. This will ignore any\n message provided\n -m, --message TEXT A message to be included in the .gitkeep file, ideally\n used to explain why it's important to push the specified\n directory to source control even if it's empty.\n -v, --verbose Print out everything.\n --help Show this message and exit.\n"
},
{
"answer_id": 56624980,
"author": "arcseldon",
"author_id": 1882064,
"author_profile": "https://Stackoverflow.com/users/1882064",
"pm_score": 3,
"selected": false,
"text": ".gitkeep"
},
{
"answer_id": 57474959,
"author": "Hainan Zhao",
"author_id": 1350922,
"author_profile": "https://Stackoverflow.com/users/1350922",
"pm_score": 3,
"selected": false,
"text": "Get-ChildItem 'Path to your Folder' -Recurse -Directory | Where-Object {[System.IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | ForEach-Object { New-Item ($_.FullName + \"\\.gitkeep\") -ItemType file}\n"
},
{
"answer_id": 58510582,
"author": "aball",
"author_id": 8213124,
"author_profile": "https://Stackoverflow.com/users/8213124",
"pm_score": 2,
"selected": false,
"text": "touch .keepdir # Ignore files but not directories. * matches both files and directories\n# but */ matches only directories. Both match at every directory level\n# at or below this one.\n*\n!*/\n\n# Git doesn't track empty directories, so track .keepdir files, which also\n# tracks the containing directory.\n!.keepdir\n\n# Keep this file and the explanation of how this works\n!.gitignore\n!Readme.md\n"
},
{
"answer_id": 58543445,
"author": "ntninja",
"author_id": 277882,
"author_profile": "https://Stackoverflow.com/users/277882",
"pm_score": 4,
"selected": false,
"text": "commit e84d7b81f0033399e325b8037ed2b801a5c994e0\nAuthor: Nobody <none>\nDate: Thu Jan 1 00:00:00 1970 +0000\n git submodule add https://gitlab.com/empty-repo/empty.git path/to/dir\n find . -type d -empty -delete -exec git submodule add -f https://gitlab.com/empty-repo/empty.git \\{\\} \\;\n e84d7b81f0033399e325b8037ed2b801a5c994e0 git submodule status # Initialize new GIT repository\ngit init\n\n# Set author data (don't set it as part of the `git commit` command or your default data will be stored as “commit author”)\ngit config --local user.name \"Nobody\"\ngit config --local user.email \"none\"\n\n# Set both the commit and the author date to the start of the Unix epoch (this cannot be done using `git commit` directly)\nexport GIT_AUTHOR_DATE=\"Thu Jan 1 00:00:00 1970 +0000\"\nexport GIT_COMMITTER_DATE=\"Thu Jan 1 00:00:00 1970 +0000\"\n\n# Add root commit\ngit commit --allow-empty --allow-empty-message --no-edit\n"
},
{
"answer_id": 58945680,
"author": "Yi Zhao",
"author_id": 6381094,
"author_profile": "https://Stackoverflow.com/users/6381094",
"pm_score": 0,
"selected": false,
"text": "Untracked files:\n (use \"git add <file>...\" to include in what will be committed)\n ../trine/device_android/\n git add new_folder/some_file\n"
},
{
"answer_id": 63726420,
"author": "DevonDahon",
"author_id": 931247,
"author_profile": "https://Stackoverflow.com/users/931247",
"pm_score": 4,
"selected": false,
"text": ".gitignore *\n*/\n!.gitignore\n * */ !.gitignore git rm -r --cached .\ngit add . // or git stage .\ngit commit -m \".gitignore fix\"\ngit push\n"
},
{
"answer_id": 63822216,
"author": "Aroo",
"author_id": 12019321,
"author_profile": "https://Stackoverflow.com/users/12019321",
"pm_score": -1,
"selected": false,
"text": "readme .gitignore"
},
{
"answer_id": 64944116,
"author": "Sohel Ahmed Mesaniya",
"author_id": 3794786,
"author_profile": "https://Stackoverflow.com/users/3794786",
"pm_score": 2,
"selected": false,
"text": "/project/content/posts /project/content/posts/.gitignore"
},
{
"answer_id": 70183273,
"author": "vidur punj",
"author_id": 1578898,
"author_profile": "https://Stackoverflow.com/users/1578898",
"pm_score": 5,
"selected": false,
"text": "touch .gitkeep\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/115983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] |
116,032
|
<p>I've sometimes had a problem with my field-, table-, view- oder stored procedure names.
Example:</p>
<pre><code> SELECT from, to, rate FROM Table1
</code></pre>
<p>The Problem is that <strong><em>from</em></strong> is a reserved word in SQL-92.
You could put the fieldname in double quotes to fix this, but what if some other db tools wants to read your database?
It is your database design and it is your fault if other applications have problems with your db.</p>
<p>There are many other <a href="http://developer.mimer.com/validator/sql-reserved-words.tml" rel="nofollow noreferrer" title="SQL reserved words">reserved words</a> (~300) and we should avoid all of them.
If you change the DBMS from manufacturer A to B, your application can fail, because a some fieldnames are now reserved words.
A field called <strong><em>PERCENT</em></strong> may work for a oracle db, but on a MS SQL Server it must be treated as a reserved word.</p>
<p>I have a tool to check my database design against these reserved words ; you too?</p>
<p>Here are my rules</p>
<ol>
<li>don't use names longer than 32 chars (some DBMS can't handle longer names)</li>
<li>use only a-z, A-Z, 0-9 and the underscore (:-;,/&!=?+- are not allowed)</li>
<li>don't start a name with a digit</li>
<li>avoid these reserved words</li>
</ol>
|
[
{
"answer_id": 292411,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 0,
"selected": false,
"text": "-- SQL -----------------------\ndeclare @sql as varchar(4000)\nset @sql = 'select \"To\", \"From\" from MyTable'\n\n' VB -------------------------\nDim sql as String\nsql = \"select \"\"To\"\", \"\"From\"\" from MyTable\"\n\n// C++ -----------------------\nString sql = \"select \\\"To\\\", \\\"From\\\" from MyTable\"\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573/"
] |
116,038
|
<p>How do I read a file into a <code>std::string</code>, i.e., read the whole file at once?</p>
<p>Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.</p>
<p>One way to do this would be to stat the filesize, resize the <code>std::string</code> and <code>fread()</code> into the <code>std::string</code>'s <code>const_cast<char*>()</code>'ed <code>data()</code>. This requires the <code>std::string</code>'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the <code>std::string</code>'s size may not equal the file's size.</p>
<p>A fully correct, standard-compliant and portable solutions could be constructed using <code>std::ifstream</code>'s <code>rdbuf()</code> into a <code>std::ostringstream</code> and from there into a <code>std::string</code>. However, this could copy the string data and/or needlessly reallocate memory. </p>
<ul>
<li>Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? </li>
<li>Is there another way to do it? </li>
<li>Did I miss some hidden Boost function that already provides the desired functionality?</li>
</ul>
<p><br></p>
<pre><code>void slurp(std::string& data, bool is_binary)
</code></pre>
|
[
{
"answer_id": 116083,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 5,
"selected": false,
"text": "#include <iostream>\n#include <sstream>\n#include <fstream>\n\nint main()\n{\n std::ifstream input(\"file.txt\");\n std::stringstream sstr;\n\n while(input >> sstr.rdbuf());\n\n std::cout << sstr.str() << std::endl;\n}\n slurp"
},
{
"answer_id": 116177,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "std::string str(std::istreambuf_iterator<char>{ifs}, {});\n <iterator> std::istream::read"
},
{
"answer_id": 116180,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "void slurp(std::string& data, const std::string& filename, bool is_binary)\n{\n std::ios_base::openmode openmode = ios::ate | ios::in;\n if (is_binary)\n openmode |= ios::binary;\n ifstream file(filename.c_str(), openmode);\n data.clear();\n data.reserve(file.tellg());\n file.seekg(0, ios::beg);\n data.append(istreambuf_iterator<char>(file.rdbuf()), \n istreambuf_iterator<char>());\n}\n"
},
{
"answer_id": 116192,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 2,
"selected": false,
"text": "std::string data;\nstd::ifstream in( \"test.txt\" );\nstd::getline( in, data, std::string::traits_type::to_char_type( \n std::string::traits_type::eof() ) );\n"
},
{
"answer_id": 116220,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "std::string std::string slurp(std::ifstream& in) {\n std::ostringstream sstr;\n sstr << in.rdbuf();\n return sstr.str();\n}\n auto read_file(std::string_view path) -> std::string {\n constexpr auto read_size = std::size_t(4096);\n auto stream = std::ifstream(path.data());\n stream.exceptions(std::ios_base::badbit);\n \n auto out = std::string();\n auto buf = std::string(read_size, '\\0');\n while (stream.read(& buf[0], read_size)) {\n out.append(buf, 0, stream.gcount());\n }\n out.append(buf, 0, stream.gcount());\n return out;\n}\n"
},
{
"answer_id": 525103,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 6,
"selected": false,
"text": "string readFile2(const string &fileName)\n{\n ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);\n\n ifstream::pos_type fileSize = ifs.tellg();\n ifs.seekg(0, ios::beg);\n\n vector<char> bytes(fileSize);\n ifs.read(bytes.data(), fileSize);\n\n return string(bytes.data(), fileSize);\n}\n"
},
{
"answer_id": 40903508,
"author": "Gabriel Majeri",
"author_id": 5723188,
"author_profile": "https://Stackoverflow.com/users/5723188",
"pm_score": 5,
"selected": false,
"text": "std::filesystem::file_size seekg tellg #include <filesystem>\n#include <fstream>\n#include <string>\n\nnamespace fs = std::filesystem;\n\nstd::string readFile(fs::path path)\n{\n // Open the stream to 'lock' the file.\n std::ifstream f(path, std::ios::in | std::ios::binary);\n\n // Obtain the size of the file.\n const auto sz = fs::file_size(path);\n\n // Create a buffer.\n std::string result(sz, '\\0');\n\n // Read the whole file into the buffer.\n f.read(result.data(), sz);\n\n return result;\n}\n <experimental/filesystem> std::experimental::filesystem result.data() &result[0]"
},
{
"answer_id": 43009155,
"author": "Rick Ramstetter",
"author_id": 1519371,
"author_profile": "https://Stackoverflow.com/users/1519371",
"pm_score": 4,
"selected": false,
"text": "tellg() tellg() tellg() ...\nstd::streamsize size = file.tellg();\nstd::vector<char> buffer(size);\n...\n tellg() tellg() vector<char> string readFile2(const string &fileName)\n{\n ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);\n\n ifstream::pos_type fileSize = ifs.tellg();\n if (fileSize < 0) <--- ADDED\n return std::string(); <--- ADDED\n\n ifs.seekg(0, ios::beg);\n\n vector<char> bytes(fileSize);\n ifs.read(&bytes[0], fileSize);\n\n return string(&bytes[0], fileSize);\n}\n"
},
{
"answer_id": 43027468,
"author": "tgnottingham",
"author_id": 1023121,
"author_profile": "https://Stackoverflow.com/users/1023121",
"pm_score": 3,
"selected": false,
"text": "std::string file_to_string(const std::string& file_name)\n{\n std::ifstream file_stream{file_name};\n\n if (file_stream.fail())\n {\n // Error opening file.\n }\n\n std::ostringstream str_stream{};\n file_stream >> str_stream.rdbuf(); // NOT str_stream << file_stream.rdbuf()\n\n if (file_stream.fail() && !file_stream.eof())\n {\n // Error reading file.\n }\n\n return str_stream.str();\n}\n str_stream << file_stream.rdbuf() str_stream.fail() && !str_stream.eof() file_stream.fail() && !file_stream.eof() file_stream >> str_stream.rdbuf()"
},
{
"answer_id": 57973715,
"author": "Paul Sumpner",
"author_id": 1429282,
"author_profile": "https://Stackoverflow.com/users/1429282",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <sstream>\n\nusing namespace std;\n\nstring GetStreamAsString(const istream& in)\n{\n stringstream out;\n out << in.rdbuf();\n return out.str();\n}\n\nstring GetFileAsString(static string& filePath)\n{\n ifstream stream;\n try\n {\n // Set to throw on failure\n stream.exceptions(fstream::failbit | fstream::badbit);\n stream.open(filePath);\n }\n catch (system_error& error)\n {\n cerr << \"Failed to open '\" << filePath << \"'\\n\" << error.code().message() << endl;\n return \"Open fail\";\n }\n\n return GetStreamAsString(stream);\n}\n const string logAsString = GetFileAsString(logFilePath);\n"
},
{
"answer_id": 58737956,
"author": "David G",
"author_id": 1435420,
"author_profile": "https://Stackoverflow.com/users/1435420",
"pm_score": 3,
"selected": false,
"text": "#include <cstdint>\n#include <exception>\n#include <filesystem>\n#include <fstream>\n#include <sstream>\n#include <string>\n\nnamespace fs = std::filesystem;\n\nstd::string loadFile(const char *const name);\nstd::string loadFile(const std::string &name);\n\nstd::string loadFile(const char *const name) {\n fs::path filepath(fs::absolute(fs::path(name)));\n\n std::uintmax_t fsize;\n\n if (fs::exists(filepath)) {\n fsize = fs::file_size(filepath);\n } else {\n throw(std::invalid_argument(\"File not found: \" + filepath.string()));\n }\n\n std::ifstream infile;\n infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n try {\n infile.open(filepath.c_str(), std::ios::in | std::ifstream::binary);\n } catch (...) {\n std::throw_with_nested(std::runtime_error(\"Can't open input file \" + filepath.string()));\n }\n\n std::string fileStr;\n\n try {\n fileStr.resize(fsize);\n } catch (...) {\n std::stringstream err;\n err << \"Can't resize to \" << fsize << \" bytes\";\n std::throw_with_nested(std::runtime_error(err.str()));\n }\n\n infile.read(fileStr.data(), fsize);\n infile.close();\n\n return fileStr;\n}\n\nstd::string loadFile(const std::string &name) { return loadFile(name.c_str()); };\n"
},
{
"answer_id": 61583878,
"author": "kiroma",
"author_id": 10286616,
"author_profile": "https://Stackoverflow.com/users/10286616",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <fstream>\n#include <limits>\n#include <string_view>\nstd::string readfile(const std::string_view path, bool binaryMode = true)\n{\n std::ios::openmode openmode = std::ios::in;\n if(binaryMode)\n {\n openmode |= std::ios::binary;\n }\n std::ifstream ifs(path.data(), openmode);\n ifs.ignore(std::numeric_limits<std::streamsize>::max());\n std::string data(ifs.gcount(), 0);\n ifs.seekg(0);\n ifs.read(data.data(), data.size());\n return data;\n}\n tellg() gcount() ignore() std::vector<char> std::string read() ignore() countg() ate tellg()"
},
{
"answer_id": 62356271,
"author": "Mashaim Tahir",
"author_id": 13250230,
"author_profile": "https://Stackoverflow.com/users/13250230",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <fstream>\n#include <string.h>\nusing namespace std;\nmain(){\n fstream file;\n //Open a file\n file.open(\"test.txt\");\n string copy,temp;\n //While loop to store whole document in copy string\n //Temp reads a complete line\n //Loop stops until temp reads the last line of document\n while(getline(file,temp)){\n //add new line text in copy\n copy+=temp;\n //adds a new line\n copy+=\"\\n\";\n }\n //Display whole document\n cout<<copy;\n //close the document\n file.close();\n}\n"
},
{
"answer_id": 63847994,
"author": "b.g.",
"author_id": 6789049,
"author_profile": "https://Stackoverflow.com/users/6789049",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n#include <string>\n#include <boost/filesystem/string_file.hpp>\n\nint main() {\n std::string result;\n boost::filesystem::load_string_file(\"aFileName.xyz\", result);\n std::cout << result.size() << std::endl;\n}\n '\\0'"
},
{
"answer_id": 69272011,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <fstream>\n#include <sstream>\nstd::string file_get_contents(const std::string &$filename)\n{\n std::ifstream file($filename, std::ifstream::binary);\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.seekg(0, std::istream::end);\n const std::streampos ssize = file.tellg();\n if (ssize < 0)\n {\n // can't get size for some reason, fallback to slower \"just read everything\"\n // because i dont trust that we could seek back/fourth in the original stream,\n // im creating a new stream.\n std::ifstream file($filename, std::ifstream::binary);\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n std::ostringstream ss;\n ss << file.rdbuf();\n return ss.str();\n }\n file.seekg(0, std::istream::beg);\n std::string result(size_t(ssize), 0);\n file.read(&result[0], std::streamsize(ssize));\n return result;\n}\n"
},
{
"answer_id": 69513374,
"author": "Roflcopter4",
"author_id": 5511137,
"author_profile": "https://Stackoverflow.com/users/5511137",
"pm_score": 0,
"selected": false,
"text": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <sys/stat.h>\n\nstatic constexpr char const filename[] = \"foo.bar\";\n\nint main(void)\n{\n FILE *fp = ::fopen(filename, \"rb\");\n if (!fp) {\n ::perror(\"fopen\");\n ::exit(1);\n }\n\n struct stat st;\n if (::fstat(fileno(fp), &st) == (-1)) {\n ::perror(\"fstat\");\n ::exit(1);\n }\n\n // You could simply allocate a buffer here and use std::string_view, or\n // even allocate a buffer and copy it to a std::string. Creating a\n // std::string and setting its size is simplest, but will pointlessly\n // initialize the buffer to 0. You can't win sometimes.\n std::string str;\n str.reserve(st.st_size + 1U);\n str.resize(st.st_size);\n ::fread(str.data(), 1, st.st_size, fp);\n str[st.st_size] = '\\0';\n ::fclose(fp);\n}\n std::string std::string::data() std::string_view"
},
{
"answer_id": 69789640,
"author": "Xavier",
"author_id": 256062,
"author_profile": "https://Stackoverflow.com/users/256062",
"pm_score": 0,
"selected": false,
"text": "std::string readAllText(std::string const &path)\n{\n assert(path.c_str() != NULL);\n FILE *stream = fopen(path.c_str(), \"r\");\n assert(stream != NULL);\n fseek(stream, 0, SEEK_END);\n long stream_size = ftell(stream);\n fseek(stream, 0, SEEK_SET);\n void *buffer = malloc(stream_size);\n fread(buffer, stream_size, 1, stream);\n assert(ferror(stream) == 0);\n fclose(stream);\n std::string text((const char *)buffer, stream_size);\n assert(buffer != NULL);\n free((void *)buffer);\n return text;\n}\n"
},
{
"answer_id": 69854038,
"author": "Sergey Abbakumov",
"author_id": 2899779,
"author_profile": "https://Stackoverflow.com/users/2899779",
"pm_score": 0,
"selected": false,
"text": "#include \"rst/files/file_utils.h\"\n\nstd::filesystem::path path = ...; // Path to a file.\nrst::StatusOr<std::string> content = rst::ReadFile(path);\nif (content.err()) {\n // Handle error.\n}\n\nstd::cout << *content << \", \" << content->size() << std::endl;\n"
},
{
"answer_id": 70499992,
"author": "Barrett",
"author_id": 17775972,
"author_profile": "https://Stackoverflow.com/users/17775972",
"pm_score": -1,
"selected": false,
"text": "#include <fstream>\n#include <string>\n\nbool fileRead( std::string &contents, const std::string &path ) {\n contents.clear();\n if( path.empty()) {\n return false;\n }\n std::ifstream stream( path );\n if( !stream ) {\n return false;\n }\n stream >> contents;\n return true;\n}\n"
},
{
"answer_id": 71066444,
"author": "Ritesh Saha",
"author_id": 14984346,
"author_profile": "https://Stackoverflow.com/users/14984346",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <fstream>\n\nint main()\n{\n std::string fileLocation = \"C:\\\\Users\\\\User\\\\Desktop\\\\file.txt\";\n std::ifstream file(fileLocation, std::ios::in | std::ios::binary);\n\n std::string data;\n\n if(file.is_open())\n {\n std::getline(file, data, '\\0');\n\n file.close();\n }\n}\n"
},
{
"answer_id": 71813338,
"author": "Andrew",
"author_id": 1599699,
"author_profile": "https://Stackoverflow.com/users/1599699",
"pm_score": 1,
"selected": false,
"text": "#include <filesystem>\n#include <fstream>\n#include <string>\n\n//Returns true if successful.\nbool readInFile(std::string pathString)\n{\n //Make sure the file exists and is an actual file.\n if (!std::filesystem::is_regular_file(pathString))\n {\n return false;\n }\n //Convert relative path to absolute path.\n pathString = std::filesystem::weakly_canonical(pathString);\n //Open the file for reading (binary is fastest).\n std::wifstream in(pathString, std::ios::binary);\n //Make sure the file opened.\n if (!in)\n {\n return false;\n }\n //Wide string to store the file's contents.\n std::wstring fileContents;\n //Jump to the end of the file to determine the file size.\n in.seekg(0, std::ios::end);\n //Resize the wide string to be able to fit the entire file (Note: Do not use reserve()!).\n fileContents.resize(in.tellg());\n //Go back to the beginning of the file to start reading.\n in.seekg(0, std::ios::beg);\n //Read the entire file's contents into the wide string.\n in.read(fileContents.data(), fileContents.size());\n //Close the file.\n in.close();\n //Do whatever you want with the file contents.\n std::wcout << fileContents << L\" \" << fileContents.size();\n return true;\n}\n std::wstring std::string"
},
{
"answer_id": 72046987,
"author": "user1095108",
"author_id": 1095108,
"author_profile": "https://Stackoverflow.com/users/1095108",
"pm_score": -1,
"selected": false,
"text": "std::string get(std::string_view const& fn)\n{\n struct filebuf: std::filebuf\n {\n using std::filebuf::egptr;\n using std::filebuf::gptr;\n\n using std::filebuf::gbump;\n using std::filebuf::underflow;\n };\n\n std::string r;\n\n if (filebuf fb; fb.open(fn.data(), std::ios::binary | std::ios::in))\n {\n r.reserve(fb.pubseekoff({}, std::ios::end));\n fb.pubseekpos({});\n\n while (filebuf::traits_type::eof() != fb.underflow())\n {\n auto const gptr(fb.gptr());\n auto const sz(fb.egptr() - gptr);\n\n fb.gbump(sz);\n r.append(gptr, sz);\n }\n }\n\n return r;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
116,050
|
<p>How do I programatically (Using C#) find out what the path is of my My Pictures folder? </p>
<p>Does this work on XP and Vista?</p>
|
[
{
"answer_id": 116061,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 7,
"selected": true,
"text": "Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5147/"
] |
116,053
|
<p>I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive.</p>
<p>I would prefer if the extra space was used in a more effective manner, possibilities include:</p>
<ul>
<li>the width of the report is reduced by the width of the hidden column</li>
<li>the extra space is distributed among the remaining columns</li>
</ul>
<p>In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option.</p>
<p>Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement.</p>
|
[
{
"answer_id": 36911788,
"author": "Petter Friberg",
"author_id": 5292302,
"author_profile": "https://Stackoverflow.com/users/5292302",
"pm_score": 4,
"selected": false,
"text": "jr:table <printWhenExpression/> <jr:column/> +----------------+--------+\n| User | Rep |\n+----------------+--------+\n| Jon Skeet | 854503 |\n| Darin Dimitrov | 652133 |\n| BalusC | 639753 |\n| Hans Passant | 616871 |\n| Me | 6487 |\n+----------------+--------+\n $P{displayRecordNumber} <printWhenExpression> jr:column <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<jasperReport xmlns=\"http://jasperreports.sourceforge.net/jasperreports\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\" name=\"reputation\" pageWidth=\"595\" pageHeight=\"842\" columnWidth=\"555\" leftMargin=\"20\" rightMargin=\"20\" topMargin=\"20\" bottomMargin=\"20\" uuid=\"a88bd694-4f90-41fc-84d0-002b90b2d73e\">\n <style name=\"table\">\n <box>\n <pen lineWidth=\"1.0\" lineColor=\"#000000\"/>\n </box>\n </style>\n <style name=\"table_TH\" mode=\"Opaque\" backcolor=\"#F0F8FF\">\n <box>\n <pen lineWidth=\"0.5\" lineColor=\"#000000\"/>\n </box>\n </style>\n <style name=\"table_CH\" mode=\"Opaque\" backcolor=\"#BFE1FF\">\n <box>\n <pen lineWidth=\"0.5\" lineColor=\"#000000\"/>\n </box>\n </style>\n <style name=\"table_TD\" mode=\"Opaque\" backcolor=\"#FFFFFF\">\n <box>\n <pen lineWidth=\"0.5\" lineColor=\"#000000\"/>\n </box>\n </style>\n <subDataset name=\"tableDataset\" uuid=\"7a53770f-0350-4a73-bfc1-48a5f6386594\">\n <field name=\"User\" class=\"java.lang.String\"/>\n <field name=\"Rep\" class=\"java.math.BigDecimal\"/>\n </subDataset>\n <parameter name=\"displayRecordNumber\" class=\"java.lang.Boolean\">\n <defaultValueExpression><![CDATA[true]]></defaultValueExpression>\n </parameter>\n <queryString>\n <![CDATA[]]>\n </queryString>\n <title>\n <band height=\"50\">\n <componentElement>\n <reportElement key=\"table\" style=\"table\" x=\"0\" y=\"0\" width=\"555\" height=\"47\" uuid=\"76ab08c6-e757-4785-a43d-b65ad4ab1dd5\"/>\n <jr:table xmlns:jr=\"http://jasperreports.sourceforge.net/jasperreports/components\" xsi:schemaLocation=\"http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd\">\n <datasetRun subDataset=\"tableDataset\" uuid=\"07e5f1c2-af7f-4373-b653-c127c47c9fa4\">\n <dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>\n </datasetRun>\n <jr:column width=\"90\" uuid=\"918270fe-25c8-4a9b-a872-91299cddbc31\">\n <printWhenExpression><![CDATA[$P{displayRecordNumber}]]></printWhenExpression>\n <jr:columnHeader style=\"table_CH\" height=\"30\" rowSpan=\"1\">\n <staticText>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"5cd6da41-01d5-4f74-99c2-06784f891d1e\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Record number]]></text>\n </staticText>\n </jr:columnHeader>\n <jr:detailCell style=\"table_TD\" height=\"30\" rowSpan=\"1\">\n <textField>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"5fe48359-0e7e-44b2-93ac-f55404189832\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>\n </textField>\n </jr:detailCell>\n </jr:column>\n <jr:column width=\"90\" uuid=\"7979d8a2-4e3c-42a7-9ff9-86f8e0b164bc\">\n <jr:columnHeader style=\"table_CH\" height=\"30\" rowSpan=\"1\">\n <staticText>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"61d5f1b6-7677-4511-a10c-1fb8a56a4b2a\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Username]]></text>\n </staticText>\n </jr:columnHeader>\n <jr:detailCell style=\"table_TD\" height=\"30\" rowSpan=\"1\">\n <textField>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"a3cdb99d-3bf6-4c66-b50c-259b9aabfaef\"/>\n <box leftPadding=\"3\" rightPadding=\"3\"/>\n <textElement verticalAlignment=\"Middle\"/>\n <textFieldExpression><![CDATA[$F{User}]]></textFieldExpression>\n </textField>\n </jr:detailCell>\n </jr:column>\n <jr:column width=\"90\" uuid=\"625e4e5e-5057-4eab-b4a9-c5b22844d25c\">\n <jr:columnHeader style=\"table_CH\" height=\"30\" rowSpan=\"1\">\n <staticText>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"e1c07cb8-a44c-4a8d-8566-5c86d6671282\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Reputation]]></text>\n </staticText>\n </jr:columnHeader>\n <jr:detailCell style=\"table_TD\" height=\"30\" rowSpan=\"1\">\n <textField pattern=\"#,##0\">\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"6be2d79f-be82-4c7b-afd9-0039fb8b3189\"/>\n <box leftPadding=\"3\" rightPadding=\"3\"/>\n <textElement textAlignment=\"Right\" verticalAlignment=\"Middle\"/>\n <textFieldExpression><![CDATA[$F{Rep}]]></textFieldExpression>\n </textField>\n </jr:detailCell>\n </jr:column>\n </jr:table>\n </componentElement>\n </band>\n </title>\n</jasperReport>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
116,054
|
<p>I'm not asking about converting a LaTeX document to html. </p>
<p>What I'd like to be able to do is have some way to use LaTeX math commands in an html document, and have it appear correctly in a browser. This could be done server or client side.</p>
|
[
{
"answer_id": 2116805,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 4,
"selected": false,
"text": "$(\".latex\").latex();\n\n\n<div class=\"latex\"> \n \\int_{0}^{\\pi}\\frac{x^{4}\\left(1-x\\right)^{4}}{1+x^{2}}dx =\\frac{22}{7}-\\pi \n</div>\n"
},
{
"answer_id": 65540803,
"author": "MattAllegro",
"author_id": 3543233,
"author_profile": "https://Stackoverflow.com/users/3543233",
"pm_score": 3,
"selected": false,
"text": "<link> <script> <head> \\( \\) \\[ \\] <body> <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n <title>Katex</title>\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css\" integrity=\"sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq\" crossorigin=\"anonymous\">\n <script defer src=\"https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js\" integrity=\"sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz\" crossorigin=\"anonymous\"></script>\n <script defer src=\"https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js\" integrity=\"sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI\" crossorigin=\"anonymous\" onload=\"renderMathInElement(document.body);\"></script>\n</head>\n\n<body>\n<p>Math can be inline like \\(2^{2x}=4\\), or displayed like:</p>\n\\[2^{3x}=8\\]\n</body>\n</html>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16970/"
] |
116,074
|
<p>I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN?</p>
<p>I am using <a href="https://en.wikipedia.org/wiki/Comparison_of_Subversion_clients#Standalone_Subversion_clients_comparison_table" rel="noreferrer">Versions</a> and <a href="http://en.wikipedia.org/wiki/TextMate" rel="noreferrer">TextMate</a> on OS X and commandline.</p>
|
[
{
"answer_id": 116075,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 11,
"selected": true,
"text": "svn:ignore svn propset svn:ignore dirname .\n svn propedit svn:ignore .\n"
},
{
"answer_id": 116097,
"author": "Greg",
"author_id": 1916,
"author_profile": "https://Stackoverflow.com/users/1916",
"pm_score": 6,
"selected": false,
"text": "svn propedit svn:ignore path/to/dir\n"
},
{
"answer_id": 116108,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 5,
"selected": false,
"text": "svn:ignore $ cd parentdir\n$ svn ps svn:ignore . 'cachedir'\n svn:ignore $ svn pe svn:ignore .\n $ svn pg svn:ignore .\n"
},
{
"answer_id": 116131,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 9,
"selected": false,
"text": "\\project\n \\source\n \\cache\n \\other\n project > svn status\nM source\n? cache\n svn:ignore cache . cache > svn proplist\nProperties on '.':\n svn:ignore\n svn:ignore > svn propget svn:ignore\ncache\n svn propdel svn:ignore\n"
},
{
"answer_id": 837581,
"author": "binco",
"author_id": 19671,
"author_profile": "https://Stackoverflow.com/users/19671",
"pm_score": 7,
"selected": false,
"text": "svn add *\n * svn add svn add --force .\n"
},
{
"answer_id": 1650336,
"author": "Kai",
"author_id": 75458,
"author_profile": "https://Stackoverflow.com/users/75458",
"pm_score": 6,
"selected": false,
"text": "svn delete svn:ignore ? svn status"
},
{
"answer_id": 3854291,
"author": "brainycat",
"author_id": 465702,
"author_profile": "https://Stackoverflow.com/users/465702",
"pm_score": 3,
"selected": false,
"text": "cd /trunk\nsvn ps svn:ignore . /cache\ncd /trunk/cache\nsvn ps svn:ignore . *\nsvn ci\n"
},
{
"answer_id": 4203434,
"author": "DerMike",
"author_id": 197574,
"author_profile": "https://Stackoverflow.com/users/197574",
"pm_score": 4,
"selected": false,
"text": "build/ temp/ *.tmp svn propset svn:ignore \"build\ntemp\n*.tmp\" .\n"
},
{
"answer_id": 6689382,
"author": "James Stroud",
"author_id": 843981,
"author_profile": "https://Stackoverflow.com/users/843981",
"pm_score": 4,
"selected": false,
"text": "svn propset svn:ignore \"cache\\\ntmp\\\nnull\\\nand_so_on\" .\n cache tmp null and_so_on"
},
{
"answer_id": 7306138,
"author": "Fedir RYKHTIK",
"author_id": 634275,
"author_profile": "https://Stackoverflow.com/users/634275",
"pm_score": 3,
"selected": false,
"text": "svn propset svn:ignore \".project\"$'\\n'\".settings\"$'\\n'\".buildpath\" \"yourpath\"\n"
},
{
"answer_id": 7396487,
"author": "Elliot Yap",
"author_id": 436558,
"author_profile": "https://Stackoverflow.com/users/436558",
"pm_score": 5,
"selected": false,
"text": "svn del --keep-local your_folder .svn svn:ignore svn pe export SVN_EDITOR=vi\n runtime\ncache\nattachments\nassets\n"
},
{
"answer_id": 12568040,
"author": "cdmo",
"author_id": 721065,
"author_profile": "https://Stackoverflow.com/users/721065",
"pm_score": 1,
"selected": false,
"text": "images/* ./images/ svn status -u ? images images"
},
{
"answer_id": 17347004,
"author": "matt burns",
"author_id": 276093,
"author_profile": "https://Stackoverflow.com/users/276093",
"pm_score": 5,
"selected": false,
"text": "foo svn rm --keep-local foo\n svn propset svn:ignore foo .\n"
},
{
"answer_id": 19240497,
"author": "Sam Watkins",
"author_id": 218294,
"author_profile": "https://Stackoverflow.com/users/218294",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n\n# svn-ignore-all\n\n# usage: \n# 1. run svn status to see what is going on at each step \n# 2. add or commit all files that you DO want to have in svn\n# 3. remove any random files that you don't want to svn:ignore\n# 4. run this script to svn:ignore everything marked '?' in output of `svn status`\n\nsvn status |\ngrep '^?' |\nsed 's/^? *//' |\nwhile read f; do\n d=`dirname \"$f\"`\n b=`basename \"$f\"`\n ignore=`svn propget svn:ignore \"$d\"`\n if [ -n \"$ignore\" ]; then\n ignore=\"$ignore\n\"\n fi\n ignore=\"$ignore$b\"\n svn propset svn:ignore \"$ignore\" \"$d\"\ndone\n #!/bin/sh\n\n# svn-ignore\n\n# usage:\n# svn-ignore file/to/ignore ...\n\nfor f; do\n d=`dirname \"$f\"`\n b=`basename \"$f\"`\n ignore=`svn propget svn:ignore \"$d\"`\n if [ -n \"$ignore\" ]; then\n ignore=\"$ignore\n\"\n fi\n ignore=\"$ignore$b\"\n svn propset svn:ignore \"$ignore\" \"$d\"\ndone\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6305/"
] |
116,090
|
<p>I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. </p>
<p>Does any one have any straight-forward code for killing a process using vb.net or c#?</p>
|
[
{
"answer_id": 116098,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "foreach ( Process p in System.Diagnostics.Process.GetProcessesByName(\"winword\") )\n{\n try\n {\n p.Kill();\n p.WaitForExit(); // possibly with a timeout\n }\n catch ( Win32Exception winException )\n {\n // process was terminating or can't be terminated - deal with it\n }\n catch ( InvalidOperationException invalidException )\n {\n // process has already exited - might be able to let this one go\n }\n}\n NotSupportedException"
},
{
"answer_id": 116107,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": false,
"text": "Process[] procs = Process.GetProcessesByName(\"winword\");\n\nforeach (Process proc in procs)\n proc.Kill();\n"
},
{
"answer_id": 116110,
"author": "Tomer Gabel",
"author_id": 11558,
"author_profile": "https://Stackoverflow.com/users/11558",
"pm_score": 1,
"selected": false,
"text": "foreach ( Process process in Process.GetProcessesByName( \"winword\" ) )\n{\n process.Kill();\n process.WaitForExit();\n}\n"
},
{
"answer_id": 116153,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 5,
"selected": false,
"text": " Dim proc = Process.GetProcessesByName(\"winword\")\n For i As Integer = 0 To proc.Count - 1\n proc(i).CloseMainWindow()\n Next i\n"
},
{
"answer_id": 135767,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 3,
"selected": false,
"text": "private bool isWordRunning() \n{\n return System.Diagnostics.Process.GetProcessesByName(\"winword\").Length > 0;\n}\n"
},
{
"answer_id": 9394596,
"author": "Vova Popov",
"author_id": 724533,
"author_profile": "https://Stackoverflow.com/users/724533",
"pm_score": 3,
"selected": false,
"text": " public bool FindAndKillProcess(string name)\n {\n //here we're going to get a list of all running processes on\n //the computer\n foreach (Process clsProcess in Process.GetProcesses()) {\n //now we're going to see if any of the running processes\n //match the currently running processes by using the StartsWith Method,\n //this prevents us from incluing the .EXE for the process we're looking for.\n //. Be sure to not\n //add the .exe to the name you provide, i.e: NOTEPAD,\n //not NOTEPAD.EXE or false is always returned even if\n //notepad is running\n if (clsProcess.ProcessName.StartsWith(name))\n {\n //since we found the proccess we now need to use the\n //Kill Method to kill the process. Remember, if you have\n //the process running more than once, say IE open 4\n //times the loop thr way it is now will close all 4,\n //if you want it to just close the first one it finds\n //then add a return; after the Kill\n try \n {\n clsProcess.Kill();\n }\n catch\n {\n return false;\n }\n //process killed, return true\n return true;\n }\n }\n //process not found, return false\n return false;\n }\n"
},
{
"answer_id": 29264826,
"author": "Ashok",
"author_id": 4713736,
"author_profile": "https://Stackoverflow.com/users/4713736",
"pm_score": -1,
"selected": false,
"text": "public partial class Form1 : Form\n{\n [ThreadStatic()]\n static Microsoft.Office.Interop.Word.Application wordObj = null;\n\n public Form1()\n {\n InitializeComponent();\n }\n\n public bool OpenDoc(string documentName)\n {\n bool bSuccss = false;\n System.Threading.Thread newThread;\n int iRetryCount;\n int iWait;\n int pid = 0;\n int iMaxRetry = 3;\n\n try\n {\n iRetryCount = 1;\n\n TRY_OPEN_DOCUMENT:\n iWait = 0;\n newThread = new Thread(() => OpenDocument(documentName, pid));\n newThread.Start();\n\n WAIT_FOR_WORD:\n Thread.Sleep(1000);\n iWait = iWait + 1;\n\n if (iWait < 60) //1 minute wait\n goto WAIT_FOR_WORD;\n else\n {\n iRetryCount = iRetryCount + 1;\n newThread.Abort();\n\n //'-----------------------------------------\n //'killing unresponsive word instance\n if ((wordObj != null))\n {\n try\n {\n Process.GetProcessById(pid).Kill();\n Marshal.ReleaseComObject(wordObj);\n wordObj = null;\n }\n catch (Exception ex)\n {\n }\n }\n\n //'----------------------------------------\n if (iMaxRetry >= iRetryCount)\n goto TRY_OPEN_DOCUMENT;\n else\n goto WORD_SUCCESS;\n }\n }\n catch (Exception ex)\n {\n bSuccss = false;\n }\n WORD_SUCCESS:\n\n return bSuccss;\n }\n\n private bool OpenDocument(string docName, int pid)\n {\n bool bSuccess = false;\n Microsoft.Office.Interop.Word.Application tWord;\n DateTime sTime;\n DateTime eTime;\n\n try\n {\n tWord = new Microsoft.Office.Interop.Word.Application();\n sTime = DateTime.Now;\n wordObj = new Microsoft.Office.Interop.Word.Application();\n eTime = DateTime.Now;\n tWord.Quit(false);\n Marshal.ReleaseComObject(tWord);\n tWord = null;\n wordObj.Visible = false;\n pid = GETPID(sTime, eTime);\n\n //now do stuff\n wordObj.Documents.OpenNoRepairDialog(docName);\n //other code\n\n if (wordObj != null)\n {\n wordObj.Quit(false);\n Marshal.ReleaseComObject(wordObj);\n wordObj = null;\n }\n bSuccess = true;\n }\n catch\n { }\n\n return bSuccess;\n }\n\n private int GETPID(System.DateTime startTime, System.DateTime endTime)\n {\n int pid = 0;\n\n try\n {\n foreach (Process p in Process.GetProcessesByName(\"WINWORD\"))\n {\n if (string.IsNullOrEmpty(string.Empty + p.MainWindowTitle) & p.HasExited == false && (p.StartTime.Ticks >= startTime.Ticks & p.StartTime.Ticks <= endTime.Ticks))\n {\n pid = p.Id;\n break;\n }\n }\n }\n catch\n {\n }\n return pid;\n }\n"
},
{
"answer_id": 41041813,
"author": "tyler_mitchell",
"author_id": 2720927,
"author_profile": "https://Stackoverflow.com/users/2720927",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Kills Processes By Name\n/// </summary>\n/// <param name=\"names\">List of Process Names</param>\nprivate void killProcesses(List<string> names)\n{\n var processes = new List<Process>();\n foreach (var name in names)\n processes.AddRange(Process.GetProcessesByName(name).ToList());\n foreach (Process p in processes)\n {\n try\n {\n p.Kill();\n p.WaitForExit();\n }\n catch (Exception ex)\n {\n // Logging\n RunProcess.insertFeedback(\"Clean Processes Failed\", ex);\n }\n }\n}\n killProcesses((new List<string>() { \"winword\", \"excel\" }));\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337/"
] |
116,096
|
<p>Can someone explain when to use each of these? They almost seem interchangeable in many cases. </p>
<p>The Custom Control gets added to the toolbar while the User Control (ascx) can not. The Custom Control does not get rendered in the Designer while the User Control does. Beyond that, how do you choose which is the right one to use? </p>
<p>Also, I am looking for the best way to access the controls from JavaScript (GetElementById). So, a point in the right direction for adding client side support would be great.</p>
|
[
{
"answer_id": 116135,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 0,
"selected": false,
"text": "document.GetElementById('<%=TheControl.ClientID%>') new Control() LoadControl"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20581/"
] |
116,139
|
<p>I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. </p>
<p>Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".</p>
|
[
{
"answer_id": 118136,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 1,
"selected": false,
"text": "<b>Looking <i>for</i> this <u>phrase</u>\n"
},
{
"answer_id": 118175,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 4,
"selected": false,
"text": ">>> import zipfile\n>>> z = zipfile.ZipFile(\"Course Outline.docx\")\n>>> \"Windows\" in z.read(\"word/document.xml\")\nTrue\n>>> \"random other string\" in z.read(\"word/document.xml\")\nFalse\n>>> z.close()\n"
},
{
"answer_id": 1737242,
"author": "romeok",
"author_id": 140863,
"author_profile": "https://Stackoverflow.com/users/140863",
"pm_score": 4,
"selected": false,
"text": "<w:p w:rsidR=\"00C07F31\" w:rsidRDefault=\"003F6D7A\">\n\n<w:r w:rsidRPr=\"003F6D7A\">\n\n<w:rPr>\n\n<w:b /> \n\n</w:rPr>\n\n<w:t>Hello</w:t> \n\n</w:r>\n\n<w:r>\n\n<w:t xml:space=\"preserve\">World.</w:t> \n\n</w:r>\n\n</w:p>\n"
},
{
"answer_id": 1979864,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": 7,
"selected": false,
"text": "# Import the module\nfrom docx import *\n\n# Open the .docx file\ndocument = opendocx('A document.docx')\n\n# Search returns true if found \nsearch(document,'your search string')\n"
},
{
"answer_id": 27377115,
"author": "edi9999",
"author_id": 1993501,
"author_profile": "https://Stackoverflow.com/users/1993501",
"pm_score": 3,
"selected": false,
"text": "docx2txt npm install -g docx2txt\ndocx2txt input.docx # This will print the text to stdout\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372664/"
] |
116,140
|
<p>I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity.</p>
<p>To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g.</p>
<pre><code><ItemGroup>
<AllAssemblyInfos Include="..\**\AssemblyInfo.cs" />
</ItemGroup>
<AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)"
ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)"
AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" />
</code></pre>
<p>Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup.</p>
<p>Anyone know how to make this work?</p>
|
[
{
"answer_id": 116253,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 4,
"selected": true,
"text": "<ItemGroup>\n <AllAssemblyInfos Include=\"..\\**\\AssemblyInfo.cs\" />\n</ItemGroup>\n\n<AssemblyInfo AssemblyTitle=\"\" AssemblyProduct=\"$(Product)\" AssemblyCompany=\"$(Company)\" AssemblyCopyright=\"$(Copyright)\" \n ComVisible=\"false\" CLSCompliant=\"false\" CodeLanguage=\"CS\" AssemblyDescription=\"$(Revision)$(BranchName)\" \n AssemblyVersion=\"$(FullVersion)\" AssemblyFileVersion=\"$(FullVersion)\" OutputFile=\"%(AllAssemblyInfos)\" />\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] |
116,142
|
<p>I would like to know if there is any way to add custom behaviour to the auto property get/set methods.</p>
<p>An obvious case I can think of is wanting every set property method to call on any <code>PropertyChanged</code> event handlers as part of a <code>System.ComponentModel.INotifyPropertyChanged</code> implementation. This would allow a class to have numerous properties that can be observed, where each property is defined using auto property syntax.</p>
<p>Basically I'm wondering if there is anything similar to either a get/set template or post get/set hook with class scope.</p>
<p>(I know the same end functionality can easily be achieved in slightly more verbose ways - I just hate duplication of a pattern)</p>
|
[
{
"answer_id": 116170,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 2,
"selected": false,
"text": "public string Name { get; set;} \n private string _name;\npublic string Name { get { return _name; } set { _name = value; } };\n"
},
{
"answer_id": 116206,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "public void SetProperty<T>(string propertyName, ref T field, T value)\n { field = value;\n NotifyPropertyChanged(propertyName);\n }\n\npublic Foo MyProperty \n { get { return _myProperty}\n set { SetProperty(\"MyProperty\",ref _myProperty, value);}\n } Foo _myProperty;\n"
},
{
"answer_id": 116246,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "public Class1 DoSomething( Class2 first, string text, decimal number ) {\n if ( null == first ) { throw new ArgumentNullException( \"first\" ); }\n if ( string.IsNullOrEmpty( text ) ) { throw new ArgumentException( \"Must be not null and longer than 0.\", \"text\" ) ; }\n if ( number < 15.7m || number > 76.57m ) { throw new OutOfRangeArgumentException( \"Minimum is 15.7 and maximum 76.57.\", \"number\"); }\n\n return new Class1( first.GetSomething( text ), number + text.Lenght );\n}\n public Class1 DoSomething( [NotNull]Class2 first, [NotNullOrEmpty]string text, [InRange( 15.7, 76.57 )]decimal number ) {\n return new Class1( first.GetSomething( text ), number + text.Lenght );\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
116,154
|
<p>I would like to have something like this:</p>
<pre><code>class Foo {
private:
int bar;
public:
void setBar(int bar);
int getBar() const;
}
class MyDialog : public CDialogImpl<MyDialog> {
BEGIN_MODEL_MAPPING()
MAP_INT_EDITOR(m_editBar, m_model, getBar, setBar);
END_MODEL_MAPPING()
// other methods and message map
private:
Foo * m_model;
CEdit m_editBar;
}
</code></pre>
<p>Also it would be great if I could provide my custom validations:</p>
<pre><code>MAP_VALIDATED_INT_EDITOR(m_editBar, m_model, getBar, setBar, validateBar)
...
bool validateBar (int value) {
// custom validation
}
</code></pre>
<p>Have anybody seen something like this?</p>
<p>P.S. I don't like DDX because it's old and it's not flexible, and I cannot use getters and setters.</p>
|
[
{
"answer_id": 161683,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 2,
"selected": false,
"text": "if #define DDX_MAP_VALIDATED_INT_EDITOR(control, variable, getter, setter, validator)\\\n if(nCtlID==control.GetDlgCtrlID())\\\n {\\\n if(bSaveAndValidate)\\\n {\\\n int const value=control.GetDlgItemInt();\\\n if(validator(value))\\\n {\\\n variable->setter(value);\\\n }\\\n else\\\n {\\\n return false;\\\n }\\\n }\\\n else\\\n {\\\n control.SetDlgItemInt(variable->getter());\\\n }\\\n }\n if variable"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14535/"
] |
116,163
|
<p>I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1</p>
<p>Delphi V7 - object pascal, standard Tquery object name query1.</p>
|
[
{
"answer_id": 116492,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 4,
"selected": true,
"text": "SELECT customers.\"Street 1\" FROM customers WHERE ...\n"
},
{
"answer_id": 117192,
"author": "Birger",
"author_id": 11485,
"author_profile": "https://Stackoverflow.com/users/11485",
"pm_score": -1,
"selected": false,
"text": "SELECT customers.[Street 1] FROM customers WHERE ...\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
116,164
|
<p>Some files in our repository are individual to each developer. For example some developers use a local database, which is configured in a properties file in the project. So each developer has different settings. When one developer commits, he always has to take care to not commit his individually configured files.</p>
<p>How do you handle this?</p>
|
[
{
"answer_id": 116224,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": -1,
"selected": false,
"text": "<property environment=\"env\" />\n<property file=\"${basedir}/online/${env.LOGNAME}.build.properties\" />\n<property file=\"${basedir}/online/${env.USERNAME}.build.properties\" />\n<property file=\"${basedir}/online/default.properties\" />\n LOGNAME davec.build.properties default.properties"
},
{
"answer_id": 116240,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 0,
"selected": false,
"text": "personal.properties database_user_name = DATABASE_USER_NAME_MUST_BE_SET_IN_PERSONAL_PROPERTIES_FILE\n Unable to login to database with username: \"DATABASE_USER_NAME_MUST_BE_SET_IN_PERSONAL_PROPERTIES_FILE\"\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
] |
116,188
|
<p>I need to do the following for the purposes of paging a query in nHibernate:</p>
<pre><code>Select count(*) from
(Select e.ID,e.Name from Object as e where...)
</code></pre>
<p>I have tried the following, </p>
<pre><code>select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...)
</code></pre>
<p>and I get an nHibernate Exception saying I cannot convert Object to int32.</p>
<p>Any ideas on the required syntax?</p>
<p><strong>EDIT</strong></p>
<p>The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with <code>Count(*)</code> because <code>Count(*) distinct</code> is not a valid syntax, and <code>distinct count(*)</code> is meaningless.</p>
|
[
{
"answer_id": 116285,
"author": "user8456",
"author_id": 8456,
"author_profile": "https://Stackoverflow.com/users/8456",
"pm_score": 0,
"selected": false,
"text": "e.Id e.Name select count(*) from Object where"
},
{
"answer_id": 117336,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 1,
"selected": false,
"text": "public IList GetOrders(int pageindex, int pagesize)\n{\n IList results = session.CreateMultiQuery()\n .Add(session.CreateQuery(\"from Orders o\").SetFirstResult(pageindex).SetMaxResults(pagesize))\n .Add(session.CreateQuery(\"select count(*) from Orders o\"))\n .List();\n return results;\n}\n [DataObjectMethod(DataObjectMethodType.Select)]\npublic DataTable GetOrders(int startRowIndex, int maximumRows)\n{\n IList result = dao.GetOrders(startRowIndex, maximumRows);\n _count = Convert.ToInt32(((IList)result[1])[0]);\n\n return DataTableFromIList((IList)result[0]); //Basically creates a DataTable from the IList of Orders\n}\n"
},
{
"answer_id": 117901,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 2,
"selected": false,
"text": " IList results = session.CreateMultiQuery()\n .Add(session.CreateQuery(\"from Orders o\").SetFirstResult(pageindex).SetMaxResults(pagesize))\n .Add(session.CreateQuery(\"select count(distinct e.Id) from Orders o where...\"))\n .List();\n return results;\n"
},
{
"answer_id": 118413,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 4,
"selected": false,
"text": "var session = GetSession();\nvar criteria = session.CreateCriteria(typeof(Order))\n .Add(Restrictions.Eq(\"Product\", product))\n .SetProjection(Projections.CountDistinct(\"Price\"));\nreturn (int) criteria.UniqueResult();\n"
},
{
"answer_id": 3283986,
"author": "Marcelo Salazar",
"author_id": 222369,
"author_profile": "https://Stackoverflow.com/users/222369",
"pm_score": 0,
"selected": false,
"text": " public IList GetOrders(int pageindex, int pagesize, out int total)\n {\n var results = session.CreateQuery().Add(session.CreateQuery(\"from Orders o\").SetFirstResult(pageindex).SetMaxResults(pagesize));\n\n var wCriteriaCount = (ICriteria)results.Clone());\n\n wCriteriaCount.SetProjection(Projections.RowCount());\n\n total = Convert.ToInt32(wCriteriaCount.UniqueResult());\n\n\n return results.List();\n }\n"
},
{
"answer_id": 4751382,
"author": "bipinkarms",
"author_id": 567072,
"author_profile": "https://Stackoverflow.com/users/567072",
"pm_score": 4,
"selected": false,
"text": "int count = session.QueryOver<Orders>().RowCount();\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14833/"
] |
116,195
|
<p>Yes XML is human readable but so is comma delimited text and properties files.</p>
<p>XML is bloated, hard to parse, hard to modify in code, plus a ton of other problems that I can think about with it. </p>
<p>My questions is what are XML's most attractive qualities that has made it so popular????</p>
|
[
{
"answer_id": 116420,
"author": "MattMcKnight",
"author_id": 8136,
"author_profile": "https://Stackoverflow.com/users/8136",
"pm_score": 0,
"selected": false,
"text": "</> <my_tag>blah</> my_tag>blah</my_tag>"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6788/"
] |
116,221
|
<p>This is not a new topic, but I am curious how everyone is handling either <code>.js</code> or <code>.css</code> that is browser specific. </p>
<p>Do you have <code>.js</code> functions that have <code>if/else</code> conditions in them or do you have separate files for each browser? </p>
<p>Is this really an issue these days with the current versions of each of the popular browsers?</p>
|
[
{
"answer_id": 116251,
"author": "neuroguy123",
"author_id": 12529,
"author_profile": "https://Stackoverflow.com/users/12529",
"pm_score": 0,
"selected": false,
"text": "jQuery.each(jQuery.browser, function(i, val) {});\n"
},
{
"answer_id": 116265,
"author": "Max Rible Kaehn",
"author_id": 2512583,
"author_profile": "https://Stackoverflow.com/users/2512583",
"pm_score": 0,
"selected": false,
"text": "<!--[if IE]>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"ie.css\" />\n<![endif]-->\n"
},
{
"answer_id": 116278,
"author": "Rakesh Pai",
"author_id": 20089,
"author_profile": "https://Stackoverflow.com/users/20089",
"pm_score": 2,
"selected": false,
"text": "document.getElementsByClassName if(document.getElementsByClassName) {\n // do something with document.getElementsByClassName\n} else {\n // find an alternative\n}\n"
},
{
"answer_id": 118445,
"author": "toohool",
"author_id": 14334,
"author_profile": "https://Stackoverflow.com/users/14334",
"pm_score": 2,
"selected": false,
"text": ".myClass {\n color: red; // Non-IE browsers will use this one\n *color: blue; // IE7 will see this one\n _color: green; // IE6 and below will see this one\n}\n"
},
{
"answer_id": 118486,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 0,
"selected": false,
"text": "<asp:Label runat=\"server\" ID=\"labelText\" \n ie:CssClass=\"IeLabelClass\" \n mozilla:CssClass=\"FirefoxLabelClass\" \n CssClass=\"GenericLabelClass\" /> \n"
},
{
"answer_id": 17817504,
"author": "Ionko Gueorguiev",
"author_id": 1830674,
"author_profile": "https://Stackoverflow.com/users/1830674",
"pm_score": 0,
"selected": false,
"text": "<!--[if lt IE 9]><div class=\"ie8-and-below\"></div><![endif]-->\n if ($(\"div\").hasClass(\"ie8-and-below\")) {\n //do you JS for IE 8 and below only\n }\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=10\" />\n <head> <head>"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8530/"
] |
116,228
|
<p>I've got a database which I intend to replicate for backup reasons (performance is not a problem at the moment). </p>
<p>We've set up the replication correctly and tested it and all was fine.</p>
<p>Then we realized that it replicates all the writes to the temporary tables, which in effect meant that replication of one day's worth of data took almost two hours for the idle slave. </p>
<p>The reason for that is that we recompute some of the data in our db via cronjob every 15 mins to ensure it's in sync (it takes ~3 minutes in total, so it is unacceptable to do those operations during a web request; instead we just store the modifications without attempting to recompute anything while in the web request, and then do all of the work in bulk). In order to process that data efficiently, we use temporary tables (as there's lots of interdependencies).</p>
<p>Now, the first problem is that temporary tables do not persist if we restart the slave while it's in the middle of processing transactions that use that temp table. That can be avoided by not using temporary tables, although this has its own issues.</p>
<p>The more serious problem is that the slave could easily catch up in less than half an hour if it wasn't for all that recomputation (which it does one after the other, so there's no benefit of rebuilding the data every 15 mins... and you can literally see it stuck at, say 1115, only to quickly catch up and got stuck at 1130 etc).</p>
<p>One solution we came up with is to move all that recomputation out of the replicated db, so that the slave doesn't replicate it. But it has disadvantages in that we'd have to prune the tables it eventually updates, making our slave in effect "castrated", ie. we'd have to recompute everything on it before we could actually use it.</p>
<p>Did anyone have a similar problem and/or how would you solve it? Am I missing something obvious?</p>
|
[
{
"answer_id": 116515,
"author": "Nick Gerakines",
"author_id": 9532,
"author_profile": "https://Stackoverflow.com/users/9532",
"pm_score": 2,
"selected": false,
"text": "[mysqld]\nreplicate-do-db = db1\nreplicate-do-table = db2.mytbl2\nreplicate-wild-do-table= database_name.%\nreplicate-wild-do-table= another_db.%\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8437/"
] |
116,276
|
<p>I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.</p>
<p>Two Questions:</p>
<ol>
<li><p>I can't seem to get the input loop to work out, what's the best practice for doing so.</p></li>
<li><p>What is the object-type going to be for the reading method? A double[], or an ArrayList?</p>
<ol>
<li><p>How do I declare method-type to be an arraylist?</p></li>
<li><p>How do I prevent the array from having more than 1000 values stored within it?</p></li>
</ol></li>
</ol>
<p>Let me show what I have so far:</p>
<pre><code>public static java.util.ArrayList readRange(double end_signal){
//read in the range and stop at end_signal
ArrayList input = new ArrayList();
Scanner kbd = new Scanner( System.in );
int count = 0;
do{
input.add(kbd.nextDouble());
System.out.println(input); //debugging
++count;
} while(input(--count) != end_signal);
return input;
}
</code></pre>
<p>Any help would be appreciated, pardon my newbieness...</p>
|
[
{
"answer_id": 116283,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "while ( input.get( input.size()-1 ) != end_signal );\n ArrayList ArrayList<Double> list = new ArrayList<Double>();\n"
},
{
"answer_id": 116293,
"author": "l_39217_l",
"author_id": 13633,
"author_profile": "https://Stackoverflow.com/users/13633",
"pm_score": 0,
"selected": false,
"text": "public static java.util.ArrayList readRange(double end_signal) {\n\n //read in the range and stop at end_signal\n\n ArrayList input = new ArrayList();\n\n Scanner kbd = new Scanner(System. in );\n int count = 0;\n\n do {\n input.add(Double.valueOf(kbd.next()));\n System.out.println(input); //debugging\n ++count;\n } while (input(--count) != end_signal);\n return input;\n}\n"
},
{
"answer_id": 116532,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": true,
"text": "import java.util.Scanner;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class InputTest{\n \n private int INPUT_LIMIT = 10000;\n\n public static void main( String [] args ) {\n InputTest test = new InputTest();\n System.out.println(\"Start typing numbers...\");\n List list = test.readRange( 2.0 );\n System.out.println(\"The input was \" + list );\n }\n\n /**\n * Read from the standar input until endSignal number is typed.\n * Also limits the amount of entered numbers to 10000;\n * @return a list with the numbers.\n */\n public List readRange( double endSignal ) {\n List<Double> input = new ArrayList<Double>();\n Scanner kdb = new Scanner( System.in );\n int count = 0;\n double number = 0;\n while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){\n System.out.println( number );\n input.add( number );\n }\n return input;\n }\n}\n"
},
{
"answer_id": 116543,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": 0,
"selected": false,
"text": "public ArrayListInput() {\n // as list\n List<Double> readRange = readRange(1.5);\n\n System.out.println(readRange);\n // converted to an array\n Double[] asArray = readRange.toArray(new Double[] {});\n System.out.println(Arrays.toString(asArray));\n}\n\npublic static List<Double> readRange(double endWith) {\n String endSignal = String.valueOf(endWith);\n List<Double> result = new ArrayList<Double>();\n Scanner input = new Scanner(System.in);\n String next;\n while (!(next = input.next().trim()).equals(endSignal)) {\n if (isDouble(next)) {\n Double doubleValue = Double.valueOf(next);\n result.add(doubleValue);\n System.out.println(\"> Input valid: \" + doubleValue);\n } else {\n System.err.println(\"> Input invalid! Try again\");\n }\n }\n // result.add(endWith); // uncomment, if last input should be in the result\n return result;\n}\n\npublic static boolean isDouble(String in) {\n return Pattern.matches(fpRegex, in);\n}\n\npublic static void main(String[] args) {\n new ArrayListInput();\n}\n\nprivate static final String Digits = \"(\\\\p{Digit}+)\";\nprivate static final String HexDigits = \"(\\\\p{XDigit}+)\";\n// an exponent is 'e' or 'E' followed by an optionally\n// signed decimal integer.\nprivate static final String Exp = \"[eE][+-]?\" + Digits;\nprivate static final String fpRegex = (\"[\\\\x00-\\\\x20]*\" + // Optional leading \"whitespace\"\n \"[+-]?(\" + // Optional sign character\n \"NaN|\" + // \"NaN\" string\n \"Infinity|\" + // \"Infinity\" string\n\n // A decimal floating-point string representing a finite positive\n // number without a leading sign has at most five basic pieces:\n // Digits . Digits ExponentPart FloatTypeSuffix\n // \n // Since this method allows integer-only strings as input\n // in addition to strings of floating-point literals, the\n // two sub-patterns below are simplifications of the grammar\n // productions from the Java Language Specification, 2nd\n // edition, section 3.10.2.\n\n // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt\n \"(((\" + Digits + \"(\\\\.)?(\" + Digits + \"?)(\" + Exp + \")?)|\" +\n\n // . Digits ExponentPart_opt FloatTypeSuffix_opt\n \"(\\\\.(\" + Digits + \")(\" + Exp + \")?)|\" +\n\n // Hexadecimal strings\n \"((\" +\n // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt\n \"(0[xX]\" + HexDigits + \"(\\\\.)?)|\" +\n\n // 0[xX] HexDigits_opt . HexDigits BinaryExponent\n // FloatTypeSuffix_opt\n \"(0[xX]\" + HexDigits + \"?(\\\\.)\" + HexDigits + \")\" +\n\n \")[pP][+-]?\" + Digits + \"))\" + \"[fFdD]?))\" + \"[\\\\x00-\\\\x20]*\");// Optional\n // trailing\n // \"whitespace\"\n if (!readRange.isEmpty()) {\n double last = readRange.get(readRange.size() - 1);\n}\n"
},
{
"answer_id": 56536105,
"author": "sagar_bhoi_188",
"author_id": 9103082,
"author_profile": "https://Stackoverflow.com/users/9103082",
"pm_score": 0,
"selected": false,
"text": "public static ArrayList<Double> readRange(double end_signal) {\n\n ArrayList<Double> input = new ArrayList<Double>();\n Scanner kbd = new Scanner( System.in );\n int count = 0;\n do{\n input.add(kbd.nextDouble());\n ++count;\n } while(input(--count) != end_signal);\nreturn input;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10636/"
] |
116,289
|
<p>I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this </p>
|
[
{
"answer_id": 116312,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 5,
"selected": false,
"text": "On Error GoTo {PROCEDURE_NAME}_Error\n\n{PROCEDURE_BODY}\n\n On Error GoTo 0\n Exit {PROCEDURE_TYPE}\n\n{PROCEDURE_NAME}_Error:\n\n LogError \"Error \" & Err.Number & \" (\" & Err.Description & \") in line \" & Erl & _\n \", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}\"\n"
},
{
"answer_id": 116320,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 3,
"selected": true,
"text": "Err\n"
},
{
"answer_id": 116367,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 1,
"selected": false,
"text": "10\n ...group of statements\n20\n ...group of statements\n30\n ...and so on\n"
},
{
"answer_id": 116498,
"author": "maero",
"author_id": 11977,
"author_profile": "https://Stackoverflow.com/users/11977",
"pm_score": 4,
"selected": false,
"text": "On Error Goto Handler\n Handler:\n Err.Raise Err.Number, \"(function_name)->\" & Err.source, Err.Description\n"
},
{
"answer_id": 128613,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 2,
"selected": false,
"text": "Error.bas Option Explicit\n\nPublic Sub ReportFrom(Source As Variant, Optional Procedure As String)\n If Err.Number Then\n 'Backup Error Contents'\n Dim ErrNumber As Long: ErrNumber = Err.Number\n Dim ErrSource As String: ErrSource = Err.Source\n Dim ErrDescription As String: ErrDescription = Err.Description\n Dim ErrHelpFile As String: ErrHelpFile = Err.HelpFile\n Dim ErrHelpContext As Long: ErrHelpContext = Err.HelpContext\n Dim ErrLastDllError As Long: ErrLastDllError = Err.LastDllError\n On Error Resume Next\n 'Retrieve Source Name'\n Dim SourceName As String\n If VarType(Source) = vbObject Then\n SourceName = TypeName(Source)\n Else\n SourceName = CStr(Source)\n End If\n If LenB(Procedure) Then\n SourceName = SourceName & \".\" & Procedure\n End If\n Err.Clear\n 'Do your normal error reporting including logging, etc'\n MsgBox \"Error \" & CStr(ErrNumber) & vbLf & \"Source: \" & ErrSource & vbCrLf & \"Procedure: \" & SourceName & vbLf & \"Description: \" & ErrDescription & vbLf & \"Last DLL Error: \" & Hex$(ErrLastDllError)\n 'Report failure in logging'\n If Err.Number Then\n MsgBox \"Additionally, the error failed to be logged properly\"\n Err.Clear\n End If\n End If\nEnd Sub\n\nPublic Sub Reraise(Optional ByVal NewSource As String)\n If LenB(NewSource) Then\n NewSource = NewSource & \" -> \" & Err.Source\n Else\n NewSource = Err.Source\n End If\n Err.Raise Err.Number, NewSource, Err.Description, Err.HelpFile, Err.HelpContext\nEnd Sub\n Public Sub Form_Load()\nOn Error Goto HError\n MsgBox 1/0\n Exit Sub\nHError:\n Error.ReportFrom Me, \"Form_Load\"\nEnd Sub\n Error.Reraise Source Procedure"
},
{
"answer_id": 39111123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "dim errhndl as string\non error goto errhndl\nerrhndl:\nmsgbox \"Error\"\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
] |
116,292
|
<p>I'm a PHP developer and now I use <a href="http://en.wikipedia.org/wiki/Notepad_%28software%29" rel="nofollow noreferrer">Notepad++</a> for code editing, but lately I've been searching for an IDE to ease my work.</p>
<p>I've looked into <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="nofollow noreferrer">Eclipse</a>, <a href="http://en.wikipedia.org/wiki/Aptana#Aptana_Studio" rel="nofollow noreferrer">Aptana Studio</a> and several others, but I'm not really decided, they all look nice enough but a bit complicated. I'm sure it'll all get easy once I get used to it, but I don't want to waste my time.</p>
<p>This is what I'm looking for:</p>
<ul>
<li>FTP support</li>
<li>Code highlight</li>
<li>SVN support would be great</li>
<li>Ruby and JavaScript would be great</li>
</ul>
|
[
{
"answer_id": 116331,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "grep -r springloops.com"
},
{
"answer_id": 3968521,
"author": "arunparamakumar",
"author_id": 516129,
"author_profile": "https://Stackoverflow.com/users/516129",
"pm_score": 0,
"selected": false,
"text": "php.net php.net"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603/"
] |
116,343
|
<p>I've googled around and found most people advocating the use of <code>kmalloc</code>, as you're guaranteed to get contiguous physical blocks of memory. However, it also seems as though <code>kmalloc</code> can fail if a contiguous <strong>physical</strong> block that you want can't be found.<br>
What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous <strong>physical</strong> block of memory in a <em>system call</em>? Is there any reason I couldn't just use <code>vmalloc</code>?<br>
Finally, if I were to allocate memory during the handling of a system call, should I specify <code>GFP_ATOMIC</code>? Is a system call executed in an atomic context?</p>
<blockquote>
<p><code>GFP_ATOMIC</code><br>
The allocation is high-priority and
does not sleep. This is the flag to
use in interrupt handlers, bottom
halves and other situations where you
cannot sleep.</p>
<p><code>GFP_KERNEL</code>
This is a normal allocation and might block. This is the flag to use
in process context code when it is safe to sleep.</p>
</blockquote>
|
[
{
"answer_id": 116351,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 2,
"selected": false,
"text": "vmalloc"
},
{
"answer_id": 33996607,
"author": "Yogeesh H T",
"author_id": 3725702,
"author_profile": "https://Stackoverflow.com/users/3725702",
"pm_score": 4,
"selected": false,
"text": "kmalloc() vmalloc() kmalloc() vmalloc() kmalloc()"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2132/"
] |
116,353
|
<p>I have a web application that needs to take a file upload from the user and upload it to a remote server. I can take input from user to server fine via file_field, but can't seem to work out the next step of uploading from server to remote. Net::HTTP doesn't do multipart forms out of the box, and I haven't been able to find another good solution. I need something that will allow me to go from user -> server -> remote instead of going user -> remote. Anyone succeeded in doing this before?</p>
|
[
{
"answer_id": 116667,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 1,
"selected": false,
"text": "BOUNDARY = \"AaB03x\"\n\ndef encode_multipartformdata(parameters = {})\n ret = String.new\n parameters.each do |key, value|\n unless value.empty?\n ret << \"\\r\\n--\" << BOUNDARY << \"\\r\\n\"\n ret << \"Content-Disposition: form-data; name=\\\"#{key}\\\"\\r\\n\\r\\n\"\n ret << value\n end\n end\n ret << \"\\r\\n--\" << BOUNDARY << \"--\\r\\n\"\nend\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13710/"
] |
116,402
|
<p>I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a <code>SQL server 2000</code> query. </p>
<pre><code>SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1
</code></pre>
<p>The <code>RECORD_CREATED_DATE</code> isn't a field in the existing table. Is there some sort of SQL Function to get this information ?</p>
|
[
{
"answer_id": 116433,
"author": "AR.",
"author_id": 1354,
"author_profile": "https://Stackoverflow.com/users/1354",
"pm_score": 1,
"selected": false,
"text": "CREATE TRIGGER trigger_RecordInsertDate\nON YourTableName\nAFTER INSERT\nAS\nBEGIN\n -- T-SQL code for inserting a record and timestamp\n -- to the audit table goes here\nEND\n"
},
{
"answer_id": 116511,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 2,
"selected": false,
"text": "CREATE TRIGGER tgr_tblMain_Insert\n ON dbo.tblMain\n AFTER INSERT\nAS \nBEGIN\n set nocount on\n\n update dbo.tblMain\n set CreatedOn = getdate(),\n CreatedBy = session_user\n where tblMain.ID = INSERTED.ID\n\nEND\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
] |
116,403
|
<p>Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done?</p>
<p>Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;)</p>
|
[
{
"answer_id": 116417,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 5,
"selected": true,
"text": "</?tag[^>]*?>\n"
},
{
"answer_id": 116451,
"author": "Benjamin Autin",
"author_id": 1440933,
"author_profile": "https://Stackoverflow.com/users/1440933",
"pm_score": 0,
"selected": false,
"text": "s/<TAG[^>]*>([^<]*)</TAG[^>]*>/\\1\n"
},
{
"answer_id": 116488,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 4,
"selected": false,
"text": "<script[^>]*?>[\\s\\S]*?<\\/script>\n <\\/?script[^>]*?>\n function stripScripts(markup) {\n return markup.replace(/<script[^>]*?>[\\s\\S]*?<\\/script>/gi, '');\n}\n\nvar safeText = stripScripts(textarea.value);\n"
},
{
"answer_id": 260586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "</?TAG\\b[^>]*?>\n <br /> <b>"
},
{
"answer_id": 315885,
"author": "Jason Kelley",
"author_id": 36790,
"author_profile": "https://Stackoverflow.com/users/36790",
"pm_score": 0,
"selected": false,
"text": "</?(?(?=b|img|a|script)notag|[a-zA-Z0-9]+)(?:\\s[a-zA-Z0-9\\-]+=?(?:([\"\",']?).*?\\1?)?)*\\s*/?>\n"
},
{
"answer_id": 878257,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 0,
"selected": false,
"text": "getElementsByTagName getElementById"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
116,415
|
<p>I'm working for a customer with a huge legacy codebase consisting of various Java en JSP based applications.</p>
<p>Most querying is done using the home-build 'orm' system. Some applications use Plain Old JDBC. Some applications are based on Hibernate (yes HQL build with plus signs is a potential problem as well). Some of the older applications are entirely writen in JSP. </p>
<p>I've found a couple of SQL inject bugs manually. But I could really use some sort of tool to search for potential weak spots.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 116478,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "PreparedStatement"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16685/"
] |
116,423
|
<p>I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic.</p>
<p>I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it.</p>
<p>Thanks,
Matt</p>
|
[
{
"answer_id": 116449,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 5,
"selected": true,
"text": "\nCREATE TEMPORARY TABLE myTopCustomers\n SELECT customers.*,count(*) num from customers join purchases using(customerID)\n join items using(itemID) GROUP BY customers.ID HAVING num > 10;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
] |
116,432
|
<p>Suppose we have a stylesheet which pulls in metadata using the key() function. In other words we have instance documents like this:</p>
<pre><code><items>
<item type="some_type"/>
<item type="another_type"/>
</items>
</code></pre>
<p>and a table of additional data we would like to associate with items during processing:</p>
<pre><code><item-meta>
<item type="some_type" meta="foo"/>
<item type="another_type" meta="bar"/>
<item type="yet_another_type" meta="baz"/>
</item-meta>
</code></pre>
<p>Finally, suppose we want to do schema validation on the instance document, restricting the type attributes to the set of types which occur in item-meta. So in the schema we want to use key/keyref instead of restriction/enumeration. This is because using restriction/enumeration will require making a separate list of valid type attributes.</p>
<p>However, it doesn't look like key/keyref will actually work. Having tried it (with MSXML 6.0) it appears the selector of a schema key won't accept the document() function in its xpath argument, so we can't examine the item-meta data, whether it appears in an external file or in the schema file itself. It looks like the only place we can look for keys is the instance document.</p>
<p>So if we really don't want to have a separate list of valid types, we have to do a pre-validation transform, pulling in the item-meta stuff, then do the validation, then do our original transform. That seems overcomplicated for what ought to be a relatively straightforward use of XML schema and stylesheets.</p>
<p>Is there a better way?</p>
|
[
{
"answer_id": 117887,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 0,
"selected": false,
"text": " <error txt=\"Invalid-Item-Type 'invalid_type'\"/>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
116,444
|
<p>By default netbeans stores it's settings in a directory called .netbeans under the user's home directory. Is it possible to change the location of this directory (especially under Windows)?</p>
<p>Thanks to James Schek I now know the answer (change the path in netbeans.conf) but that leads me to another question:
Is there a way to include the current username in the path to the netbeans setting directory? </p>
<p>I want to do something like this:</p>
<pre><code>netbeans_default_userdir="D:\etc\${USERNAME}\.netbeans\6.5beta"
</code></pre>
<p>but I can't figure out the name of the variable to use (if there's any).
Of course I can achieve the same thing with the --userdir option, I'm just curious.</p>
|
[
{
"answer_id": 27975026,
"author": "pipepiper",
"author_id": 2080352,
"author_profile": "https://Stackoverflow.com/users/2080352",
"pm_score": 2,
"selected": false,
"text": "c:\\Portable\\Netbeans netbeans_default_userdir=\"c:\\Portable\\Netbeans\\userdir\\8.0\" netbeans_default_userdir=\"c:\\Portable\\NetbeansUserDir\\8.0\""
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4497/"
] |
116,469
|
<p>Ok so before I even ask my question I want to make one thing clear. I am currently a student at NIU for Computer Science and this does relate to one of my assignments for a class there. So if anyone has a problem read no further and just go on about your business. </p>
<p>Now for anyone who is willing to help heres the situation. For my current assignment we have to read a file that is just a block of text. For each word in the file we are to clear any punctuation in the word (ex : "can't" would end up as "can" and "that--to" would end up as "that" obviously with out the quotes, quotes were used just to specify what the example was).</p>
<p>The problem I've run into is that I can clean the string fine and then insert it into the map that we are using but for some reason with the code I have written it is allowing an empty string to be inserted into the map. Now I've tried everything that I can come up with to stop this from happening and the only thing I've come up with is to use the erase method within the map structure itself.</p>
<p>So what I am looking for is two things, any suggestions about how I could a) fix this with out simply just erasing it and b) any improvements that I could make on the code I already have written.</p>
<p>Here are the functions I have written to read in from the file and then the one that cleans it. </p>
<p>Note: the function that reads in from the file calls the clean_entry function to get rid of punctuation before anything is inserted into the map.</p>
<p>Edit: Thank you Chris. Numbers are allowed :). If anyone has any improvements to the code I've written or any criticisms of something I did I'll listen. At school we really don't get feed back on the correct, proper, or most efficient way to do things.</p>
<pre><code>int get_words(map<string, int>& mapz)
{
int cnt = 0; //set out counter to zero
map<string, int>::const_iterator mapzIter;
ifstream input; //declare instream
input.open( "prog2.d" ); //open instream
assert( input ); //assure it is open
string s; //temp strings to read into
string not_s;
input >> s;
while(!input.eof()) //read in until EOF
{
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
input >>s;
}
input.close(); //close instream
for(mapzIter = mapz.begin(); mapzIter != mapz.end(); mapzIter++)
cnt = cnt + mapzIter->second;
return cnt; //return number of words in instream
}
void clean_entry(const string& non_clean, string& clean)
{
int i, j, begin, end;
for(i = 0; isalnum(non_clean[i]) == 0 && non_clean[i] != '\0'; i++);
begin = i;
if(begin ==(int)non_clean.length())
return;
for(j = begin; isalnum(non_clean[j]) != 0 && non_clean[j] != '\0'; j++);
end = j;
clean = non_clean.substr(begin, (end-begin));
for(i = 0; i < (int)clean.size(); i++)
clean[i] = tolower(clean[i]);
}
</code></pre>
|
[
{
"answer_id": 116510,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": true,
"text": "not_s = \"\";\nclean_entry(s, not_s);\n\nif((int)not_s.length() == 0)\n {\n input >> s;\n clean_entry(s, not_s);\n } \n\nmapz[not_s]++; //increment occurence\ninput >>s;\n not_s = \"\";\nclean_entry(s, not_s);\n\nif((int)not_s.length() > 0)\n{\n mapz[not_s]++; //increment occurence\n} \n\ninput >>s;\n"
},
{
"answer_id": 116555,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 1,
"selected": false,
"text": "if (!not_s.empty())\n mapz[not_s]++;\n string not_s = clean_entry(s);\n...\nstring clean_entry(const string &non_clean)\n{\n string clean;\n ... // as before \n if(begin ==(int)non_clean.length())\n return clean;\n ... // as before\n return clean;\n }\n"
},
{
"answer_id": 116616,
"author": "MP24",
"author_id": 6206,
"author_profile": "https://Stackoverflow.com/users/6206",
"pm_score": 2,
"selected": false,
"text": "++mapzIter"
},
{
"answer_id": 116839,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 1,
"selected": false,
"text": "bool getNextWord (std::ifstream & input, std::string & str);\nbool getNextCleanWord (std::ifstream & input, std::string & str);\n std::string nextCleanWord;\nwhile (getNextCleanWord (input, nextCleanWord))\n{\n ++map[nextCleanWord];\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924/"
] |
116,485
|
<p>I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two.</p>
<p>This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record)</p>
<p>Right now, I have a simple:</p>
<pre><code>matches += array1[0] == array2[0];
</code></pre>
<p>repeated 16 times (as profiling it appears to be 30% faster than doing it with a for loop)</p>
<p>Is there any other way that could work faster?</p>
<p>Some data about the environment and the data itself:</p>
<ul>
<li>I'm using C++Builder, which doesn't have any speed optimizations to take into account. I will try eventually with another compiler, but right now I'm stuck with this one.</li>
<li>The data will be different most of the times. 100% equal data is usually very very rare (maybe less than 1%)</li>
</ul>
|
[
{
"answer_id": 116504,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 0,
"selected": false,
"text": "matches += (array1[0] == array2[0]) + (array1[1] == array2[1]) + ...;\n"
},
{
"answer_id": 116563,
"author": "Justsalt",
"author_id": 13693,
"author_profile": "https://Stackoverflow.com/users/13693",
"pm_score": 0,
"selected": false,
"text": "p1 = &array1[0];\np2 = &array2[0];\nmatch += (*p1++ == *p2++);\n// copy 15 times.\n"
},
{
"answer_id": 116582,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 3,
"selected": false,
"text": "int* array1 = (int*)byteArray[0];\nint* array2 = (int*)byteArray[1];\n\nint same = 0;\n\nfor (int i = 0; i < 4; i++)\n{\n // test as an int\n if (array1[i] == array2[i])\n {\n same += 4;\n }\n else\n {\n // test individual bytes\n char* bytes1 = (char*)(array1+i);\n char* bytes2 = (char*)(array2+i);\n\n for (int j = 0; j < 4; j++)\n {\n same += (bytes1[j] == bytes2[j];\n }\n }\n}\n // depending on compiler you may have to insert the words via an intrinsic\n__m128 qw1 = *(__m128*)byteArray[0];\n__m128 qw2 = *(__m128*)byteArray[1];\n\n// again, depending on the compiler the comparision may have to be done via an intrinsic\nif (qw1 == qw2)\n{\n same = 16;\n}\nelse\n{\n // do int/byte testing\n}\n"
},
{
"answer_id": 116636,
"author": "Kent Knox",
"author_id": 17227,
"author_profile": "https://Stackoverflow.com/users/17227",
"pm_score": 5,
"selected": true,
"text": "#include \"stdafx.h\"\n#include <iostream>\n#include \"intrin.h\"\n\ninline unsigned cmpArray16( char (&arr1)[16], char (&arr2)[16] )\n{\n __m128i first = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr1 ) );\n __m128i second = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr2 ) );\n\n return _mm_movemask_epi8( _mm_cmpeq_epi8( first, second ) );\n}\n\nint _tmain( int argc, _TCHAR* argv[] )\n{\n unsigned count = 0;\n char arr1[16] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 };\n char arr2[16] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 };\n\n count = __popcnt( cmpArray16( arr1, arr2 ) );\n\n std::cout << \"The number of equivalent bytes = \" << count << std::endl;\n\n return 0;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16772/"
] |
116,494
|
<p>How would one write a regular expression to use in Python to split paragraphs?</p>
<p>A paragraph is defined by two line breaks (\n). But one can have any amount of spaces/tabs together with the line breaks, and it still should be considered as a paragraph.</p>
<p>I am using Python, so the solution can use Python's <a href="https://docs.python.org/2/library/re.html" rel="nofollow noreferrer">regular expression syntax</a> which is extended. (can make use of <code>(?P...)</code> stuff)</p>
<h3>Examples:</h3>
<pre><code>the_str = 'paragraph1\n\nparagraph2'
# Splitting should yield ['paragraph1', 'paragraph2']
the_str = 'p1\n\t\np2\t\n\tstill p2\t \n \n\tp3'
# Should yield ['p1', 'p2\t\n\tstill p2', 'p3']
the_str = 'p1\n\n\n\tp2'
# Should yield ['p1', '\n\tp2']
</code></pre>
<p>The best I could come with is: <code>r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*'</code>, i.e.</p>
<pre><code>import re
paragraphs = re.split(r'[ \t\r\f\v]*\n[ \t\r\f\v]*\n[ \t\r\f\v]*', the_str)
</code></pre>
<p>But that is ugly. Is there anything better?</p>
<h3>Suggestions rejected:</h3>
<p><code>r'\s*?\n\s*?\n\s*?'</code> -> That would make example 2 and 3 fail, since <code>\s</code> includes <code>\n</code>, so it would allow paragraph breaks with more than 2 <code>\n</code>s.</p>
|
[
{
"answer_id": 116557,
"author": "Joseph Bui",
"author_id": 3275,
"author_profile": "https://Stackoverflow.com/users/3275",
"pm_score": 0,
"selected": false,
"text": "\\s*?\\n\\s*?\\n\\s*?\n"
},
{
"answer_id": 116622,
"author": "Eevee",
"author_id": 17875,
"author_profile": "https://Stackoverflow.com/users/17875",
"pm_score": 4,
"selected": true,
"text": "x (?x) (?: [ \\t\\r\\f\\v]*? \\n ){2} [ \\t\\r\\f\\v]*?"
},
{
"answer_id": 123806,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "from itertools import groupby\n\ndef paragraph(lines):\n for group_separator, line_iteration in groupby(lines.splitlines(True), key = str.isspace):\n if not group_separator:\n yield ''.join(line_iteration)\n\nfor p in paragraph('p1\\n\\t\\np2\\t\\n\\tstill p2\\t \\n \\n\\tp'):\n print repr(p)\n\n'p1\\n'\n'p2\\t\\n\\tstill p2\\t \\n'\n'\\tp3'\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17160/"
] |
116,506
|
<p>By default, emacs 22.1.1 only shows the top of the compilation buffer when you first issue the compile command. I would like it to scroll to the bottom automatically when I use the compile command in order to save keystrokes. This way I can easily get a status of the current compilation by just looking at the compile buffer and seeing which files are currently being compiled instead of having to switch windows and scroll to the bottom of the buffer. Any ideas?</p>
|
[
{
"answer_id": 116513,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": true,
"text": "compilation-scroll-output nil"
},
{
"answer_id": 122539,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 3,
"selected": false,
"text": "next-error previous-error"
},
{
"answer_id": 2020756,
"author": "Teemu Kurppa",
"author_id": 106288,
"author_profile": "https://Stackoverflow.com/users/106288",
"pm_score": 4,
"selected": false,
"text": "(setq compilation-scroll-output 'first-error)\n next-error previous-error"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
] |
116,523
|
<p>In C# there are <code>String</code> objects and <code>string</code> objects. </p>
<p>What is the difference between the two?
What are the best practices regarding which to use?</p>
|
[
{
"answer_id": 116536,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": ".method private hidebysig static void Main(string[] args) cil managed\n"
},
{
"answer_id": 116544,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 4,
"selected": false,
"text": "string foo = \"bar\";\n\nif( foo != String.Empty )\n{\n Console.WriteLine(String.Format(\"foo.Length = {0}\", foo.Length));\n}\n"
},
{
"answer_id": 116549,
"author": "Joannes Vermorel",
"author_id": 18858,
"author_profile": "https://Stackoverflow.com/users/18858",
"pm_score": 4,
"selected": false,
"text": "System.String string string"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
116,525
|
<p>I have writtent some Oracle storedprocedures in these there are more then 20 input parameters and from them morethen 10 parameters are required , I want all with some value and do not want to accept null values for that , Is there anything that I can declare in the Procedure defination itself which can restrict null input parameter or Will I have to check for each value and Raise the exception if the required value is null ?</p>
|
[
{
"answer_id": 18380487,
"author": "Neil Vass",
"author_id": 607861,
"author_profile": "https://Stackoverflow.com/users/607861",
"pm_score": 4,
"selected": false,
"text": "SUBTYPE varchar2_not_null IS VARCHAR2 NOT NULL;\n number_not_null NULL cannot pass NULL to a NOT NULL constrained formal parameter\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
] |
116,527
|
<p>Killing the processs while obtaining this information would be fine.</p>
|
[
{
"answer_id": 116606,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 2,
"selected": false,
"text": "ObjectSpace.each_object{|e| p e}"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14796/"
] |
116,535
|
<p>When writing an app that one wants to have compile on mac, linux and windows, what is the best way of managing the different libraries that will need to be included on the various operating systems. For example, using the glut opengl toolkit requires different includes on each operating system. </p>
|
[
{
"answer_id": 116562,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 0,
"selected": false,
"text": "./configure\nmake\nmake install\n"
},
{
"answer_id": 116638,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 0,
"selected": false,
"text": "#ifdef"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
116,560
|
<p>I like to use Emacs' shell mode, but it has a few deficiencies. One of those is that it's not smart enough to open a new buffer when a shell command tries to invoke an editor. For example with the environment variable <code>VISUAL</code> set to <code>vim</code> I get the following from <code>svn propedit</code>:</p>
<pre>
$ svn propedit svn:externals .
"svn-prop.tmp" 2L, 149C[1;1H
~ [4;1H~ [5;1H~ [6;1H~ [7;1H~
...
</pre>
<p>(It may be hard to tell from the representation, but it's a horrible, ugly mess.)</p>
<p>With <code>VISUAL</code> set to <code>"emacs -nw"</code>, I get</p>
<pre>
$ svn propedit svn:externals .
emacs: Terminal type "dumb" is not powerful enough to run Emacs.
It lacks the ability to position the cursor.
If that is not the actual type of terminal you have,
use the Bourne shell command `TERM=... export TERM' (C-shell:
`setenv TERM ...') to specify the correct type. It may be necessary
to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.svn: system('emacs -nw svn-prop.tmp') returned 256
</pre>
<p>(It works with <code>VISUAL</code> set to just <code>emacs</code>, but only from inside an Emacs X window, not inside a terminal session.)</p>
<p>Is there a way to get shell mode to do the right thing here and open up a new buffer on behalf of the command line process?</p>
|
[
{
"answer_id": 116570,
"author": "Rich",
"author_id": 20640,
"author_profile": "https://Stackoverflow.com/users/20640",
"pm_score": 5,
"selected": true,
"text": "emacsclient M-x server-start\n (server-start) .emacs export VISUAL=emacsclient\n emacs emacsclient emacsclient (server-start) .emacs"
},
{
"answer_id": 437748,
"author": "jrockway",
"author_id": 8457,
"author_profile": "https://Stackoverflow.com/users/8457",
"pm_score": 0,
"selected": false,
"text": "ansi-term eshell screen"
},
{
"answer_id": 10133605,
"author": "Bill",
"author_id": 1330446,
"author_profile": "https://Stackoverflow.com/users/1330446",
"pm_score": 0,
"selected": false,
"text": "Debugger entered--Lisp error: (void-function start-server)\n (start-server)\n eval-buffer(#<buffer *load*> nil \"/Users/jarrold/.emacs\" nil t) ; Reading at buffer position 22768\n load-with-code-conversion(\"/Users/jarrold/.emacs\" \"/Users/jarrold/.emacs\" t t)\n load(\"~/.emacs\" t t)\n #[nil \"^H\\205\\276^@ \\306=\\203^Q^@\\307^H\\310Q\\202A^@ \\311=\\2033^@\\312\\307\\313\\314#\\203#^@\\315\\202A^@\\312\\307\\$\n command-line()\n normal-top-level()\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
116,574
|
<p>While googling, I see that using <a href="http://docs.oracle.com/javase/6/docs/api/java/io/File.html#length%28%29" rel="noreferrer"><code>java.io.File#length()</code></a> can be slow.
<a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html" rel="noreferrer"><code>FileChannel</code></a> has a <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html#size%28%29" rel="noreferrer"><code>size()</code></a> method that is available as well.</p>
<p>Is there an efficient way in java to get the file size?</p>
|
[
{
"answer_id": 116916,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": 8,
"selected": true,
"text": "LENGTH sum: 10626, per Iteration: 10626.0\n\nCHANNEL sum: 5535, per Iteration: 5535.0\n\nURL sum: 660, per Iteration: 660.0\n LENGTH sum: 39496, per Iteration: 157.984\n\nCHANNEL sum: 74261, per Iteration: 297.044\n\nURL sum: 95534, per Iteration: 382.136\n import java.io.*;\nimport java.net.*;\nimport java.util.*;\n\npublic enum FileSizeBench {\n\n LENGTH {\n @Override\n public long getResult() throws Exception {\n File me = new File(FileSizeBench.class.getResource(\n \"FileSizeBench.class\").getFile());\n return me.length();\n }\n },\n CHANNEL {\n @Override\n public long getResult() throws Exception {\n FileInputStream fis = null;\n try {\n File me = new File(FileSizeBench.class.getResource(\n \"FileSizeBench.class\").getFile());\n fis = new FileInputStream(me);\n return fis.getChannel().size();\n } finally {\n fis.close();\n }\n }\n },\n URL {\n @Override\n public long getResult() throws Exception {\n InputStream stream = null;\n try {\n URL url = FileSizeBench.class\n .getResource(\"FileSizeBench.class\");\n stream = url.openStream();\n return stream.available();\n } finally {\n stream.close();\n }\n }\n };\n\n public abstract long getResult() throws Exception;\n\n public static void main(String[] args) throws Exception {\n int runs = 5;\n int iterations = 50;\n\n EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);\n\n for (int i = 0; i < runs; i++) {\n for (FileSizeBench test : values()) {\n if (!durations.containsKey(test)) {\n durations.put(test, 0l);\n }\n long duration = testNow(test, iterations);\n durations.put(test, durations.get(test) + duration);\n // System.out.println(test + \" took: \" + duration + \", per iteration: \" + ((double)duration / (double)iterations));\n }\n }\n\n for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {\n System.out.println();\n System.out.println(entry.getKey() + \" sum: \" + entry.getValue() + \", per Iteration: \" + ((double)entry.getValue() / (double)(runs * iterations)));\n }\n\n }\n\n private static long testNow(FileSizeBench test, int iterations)\n throws Exception {\n long result = -1;\n long before = System.nanoTime();\n for (int i = 0; i < iterations; i++) {\n if (result == -1) {\n result = test.getResult();\n //System.out.println(result);\n } else if ((result = test.getResult()) != result) {\n throw new Exception(\"variance detected!\");\n }\n }\n return (System.nanoTime() - before) / 1000;\n }\n\n}\n"
},
{
"answer_id": 119362,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "import java.io.*;\nimport java.nio.channels.*;\nimport java.net.*;\nimport java.util.*;\n\npublic class FileSizeBench {\n\n private static File file;\n private static FileChannel channel;\n private static RandomAccessFile raf;\n\n public static void main(String[] args) throws Exception {\n int runs = 1;\n int iterations = 1;\n\n file = new File(args[0]);\n channel = new FileInputStream(args[0]).getChannel();\n raf = new RandomAccessFile(args[0], \"r\");\n\n HashMap<String, Double> times = new HashMap<String, Double>();\n times.put(\"file\", 0.0);\n times.put(\"channel\", 0.0);\n times.put(\"raf\", 0.0);\n\n long start;\n for (int i = 0; i < runs; ++i) {\n long l = file.length();\n\n start = System.nanoTime();\n for (int j = 0; j < iterations; ++j)\n if (l != file.length()) throw new Exception();\n times.put(\"file\", times.get(\"file\") + System.nanoTime() - start);\n\n start = System.nanoTime();\n for (int j = 0; j < iterations; ++j)\n if (l != channel.size()) throw new Exception();\n times.put(\"channel\", times.get(\"channel\") + System.nanoTime() - start);\n\n start = System.nanoTime();\n for (int j = 0; j < iterations; ++j)\n if (l != raf.length()) throw new Exception();\n times.put(\"raf\", times.get(\"raf\") + System.nanoTime() - start);\n }\n for (Map.Entry<String, Double> entry : times.entrySet()) {\n System.out.println(\n entry.getKey() + \" sum: \" + 1e-3 * entry.getValue() +\n \", per Iteration: \" + (1e-3 * entry.getValue() / runs / iterations));\n }\n }\n}\n"
},
{
"answer_id": 1803626,
"author": "Karthikeyan",
"author_id": 219105,
"author_profile": "https://Stackoverflow.com/users/219105",
"pm_score": 3,
"selected": false,
"text": "file totalTime: 48000 (48 us)\nraf totalTime: 261000 (261 us)\nchannel totalTime: 7020000 (7 ms)\n file totalTime: 80074000 (80 ms)\nraf totalTime: 295417000 (295 ms)\nchannel totalTime: 368239000 (368 ms)\n import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.RandomAccessFile;\nimport java.nio.channels.FileChannel;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class FileSizeBench\n{ \n public static void main(String[] args) throws Exception\n {\n int iterations = 1;\n String fileEntry = args[0];\n\n Map<String, Long> times = new HashMap<String, Long>();\n times.put(\"file\", 0L);\n times.put(\"channel\", 0L);\n times.put(\"raf\", 0L);\n\n long fileSize;\n long start;\n long end;\n File f1;\n FileChannel channel;\n RandomAccessFile raf;\n\n for (int i = 0; i < iterations; i++)\n {\n // file.length()\n start = System.nanoTime();\n f1 = new File(fileEntry);\n fileSize = f1.length();\n end = System.nanoTime();\n times.put(\"file\", times.get(\"file\") + end - start);\n\n // channel.size()\n start = System.nanoTime();\n channel = new FileInputStream(fileEntry).getChannel();\n fileSize = channel.size();\n channel.close();\n end = System.nanoTime();\n times.put(\"channel\", times.get(\"channel\") + end - start);\n\n // raf.length()\n start = System.nanoTime();\n raf = new RandomAccessFile(fileEntry, \"r\");\n fileSize = raf.length();\n raf.close();\n end = System.nanoTime();\n times.put(\"raf\", times.get(\"raf\") + end - start);\n }\n\n for (Map.Entry<String, Long> entry : times.entrySet()) {\n System.out.println(entry.getKey() + \" totalTime: \" + entry.getValue() + \" (\" + getTime(entry.getValue()) + \")\");\n }\n }\n\n public static String getTime(Long timeTaken)\n {\n if (timeTaken < 1000) {\n return timeTaken + \" ns\";\n } else if (timeTaken < (1000*1000)) {\n return timeTaken/1000 + \" us\"; \n } else {\n return timeTaken/(1000*1000) + \" ms\";\n } \n }\n}\n"
},
{
"answer_id": 5385588,
"author": "StuartH",
"author_id": 670402,
"author_profile": "https://Stackoverflow.com/users/670402",
"pm_score": 4,
"selected": false,
"text": "---\nLENGTH sum: 1163351, per Iteration: 4653.404\nCHANNEL sum: 1094598, per Iteration: 4378.392\nURL sum: 739691, per Iteration: 2958.764\n\n---\nCHANNEL sum: 845804, per Iteration: 3383.216\nURL sum: 531334, per Iteration: 2125.336\nLENGTH sum: 318413, per Iteration: 1273.652\n\n--- \nURL sum: 137368, per Iteration: 549.472\nLENGTH sum: 18677, per Iteration: 74.708\nCHANNEL sum: 142125, per Iteration: 568.5\n"
},
{
"answer_id": 19430142,
"author": "RoundPi",
"author_id": 833538,
"author_profile": "https://Stackoverflow.com/users/833538",
"pm_score": 2,
"selected": false,
"text": "CHANNEL sum: 59691, per Iteration: 238.764\n LENGTH sum: 48268, per Iteration: 193.072\n @Override\npublic long getResult() throws Exception {\n File me = new File(FileSizeBench.class.getResource(\n \"FileSizeBench.class\").getFile());\n return me.length();\n}\n"
},
{
"answer_id": 21307552,
"author": "Scg",
"author_id": 3227648,
"author_profile": "https://Stackoverflow.com/users/3227648",
"pm_score": 2,
"selected": false,
"text": "Files.walkFileTree BasicFileAttributes .length() File.listFiles() Files.size() Files.newDirectoryStream()"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
] |
116,577
|
<p>Looking for suggestions on file system management tools. We have several terabytes of images, pdfs, excel sheets, etc.</p>
<p>We're looking at some sort of software that will help us to manage, archive, etc the images. </p>
<p>We don't store all the files information in a database but some are and we were hoping to maybe find an app that could help us integrate the archive process into the database.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 118529,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "cp"
},
{
"answer_id": 139771,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 0,
"selected": false,
"text": "archivedirectory cd archivedirectory\ndel oldlist.txt\nrename newlist.txt oldlist.txt\ndir /s /b > newlist.txt\n diff diff oldlist.txt newlist.txt > newfiles.txt\n newfiles.txt > grep sed"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94571/"
] |
116,579
|
<p>I'm developing a Mac App in Java that logs into any one of our client's databases. My users want to have several copies of this program running so they can log into a couple clients at the same time, rather than logging out and logging back in.</p>
<p>How can I allow a user to open several copies of my App at once?</p>
<p>I'm using Eclipse to develop, and Jarbundler to make the app.</p>
<p>Edit: More Importantly, is there a way to do so in the code base, rather than have my user do something funky on their system? I'd rather just give them a 'Open New Window' menu item, then have them typing things into the Terminal.</p>
|
[
{
"answer_id": 116903,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 0,
"selected": false,
"text": "/Applications/TextEdit.app/Contents/MacOS/TextEdit &\n String[] cmd = { \"/bin/sh\", \"-c\", \"[shell commmand goes here]\" };\n Process p = Runtime.getRuntime().exec (cmd);\n"
},
{
"answer_id": 117277,
"author": "DyreSchlock",
"author_id": 738,
"author_profile": "https://Stackoverflow.com/users/738",
"pm_score": 0,
"selected": false,
"text": "open -n -a appName.app\n tell application \"Terminal\"\nactivaate\n do script \"open -n -a appName.app\"\nend tell\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738/"
] |
116,587
|
<p>I need to determine if a Class object representing an interface extends another interface, ie:</p>
<pre><code> package a.b.c.d;
public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{
}
</code></pre>
<p>according to <a href="http://web.archive.org/web/20100705124350/http://java.sun.com:80/j2se/1.4.2/docs/api/java/lang/Class.html" rel="nofollow noreferrer">the spec</a> Class.getSuperClass() will return null for an Interface. </p>
<blockquote>
<p>If this Class represents either the
Object class, an interface, a
primitive type, or void, then null is
returned.</p>
</blockquote>
<p>Therefore the following won't work.</p>
<pre><code>Class interface = Class.ForName("a.b.c.d.IMyInterface")
Class extendedInterface = interface.getSuperClass();
if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){
//do whatever here
}
</code></pre>
<p>any ideas?</p>
|
[
{
"answer_id": 116615,
"author": "Andreas Holstenson",
"author_id": 16351,
"author_profile": "https://Stackoverflow.com/users/16351",
"pm_score": 5,
"selected": true,
"text": "Class<?> c; // Your class\nfor(Class<?> i : c.getInterfaces()) {\n // test if i is your interface\n}\n public static Set<Class<?>> getInheritance(Class<?> in)\n{\n LinkedHashSet<Class<?>> result = new LinkedHashSet<Class<?>>();\n\n result.add(in);\n getInheritance(in, result);\n\n return result;\n}\n\n/**\n * Get inheritance of type.\n * \n * @param in\n * @param result\n */\nprivate static void getInheritance(Class<?> in, Set<Class<?>> result)\n{\n Class<?> superclass = getSuperclass(in);\n\n if(superclass != null)\n {\n result.add(superclass);\n getInheritance(superclass, result);\n }\n\n getInterfaceInheritance(in, result);\n}\n\n/**\n * Get interfaces that the type inherits from.\n * \n * @param in\n * @param result\n */\nprivate static void getInterfaceInheritance(Class<?> in, Set<Class<?>> result)\n{\n for(Class<?> c : in.getInterfaces())\n {\n result.add(c);\n\n getInterfaceInheritance(c, result);\n }\n}\n\n/**\n * Get superclass of class.\n * \n * @param in\n * @return\n */\nprivate static Class<?> getSuperclass(Class<?> in)\n{\n if(in == null)\n {\n return null;\n }\n\n if(in.isArray() && in != Object[].class)\n {\n Class<?> type = in.getComponentType();\n\n while(type.isArray())\n {\n type = type.getComponentType();\n }\n\n return type;\n }\n\n return in.getSuperclass();\n}\n"
},
{
"answer_id": 116619,
"author": "user13664",
"author_id": 13664,
"author_profile": "https://Stackoverflow.com/users/13664",
"pm_score": 0,
"selected": false,
"text": "List<Object> list = new ArrayList<Object>();\nfor (Class c : list.getClass().getInterfaces()) {\n System.out.println(c.getName());\n}\n"
},
{
"answer_id": 116625,
"author": "Dan Fleet",
"author_id": 7470,
"author_profile": "https://Stackoverflow.com/users/7470",
"pm_score": 2,
"selected": false,
"text": "Class baseInterface = Class.forName(\"a.b.c.d.IMyInterface\");\nClass extendedInterface = Class.forName(\"a.b.d.c.ISomeOtherInterface\");\n\nif ( baseInterface.isAssignableFrom(extendedInterface) )\n{\n // do stuff\n}\n"
},
{
"answer_id": 116633,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 3,
"selected": false,
"text": "if (interface.isAssignableFrom(extendedInterface))\n if (extendedInterfaceA instanceof interfaceB) \n"
},
{
"answer_id": 46471033,
"author": "PhantomStr",
"author_id": 8690096,
"author_profile": "https://Stackoverflow.com/users/8690096",
"pm_score": 0,
"selected": false,
"text": "Liast<Class> getAllInterfaces(Class<?> clazz){\n List<Class> interfaces = new ArrayList<>();\n Collections.addAll(interfaces,clazz.getInterfaces());\n if(!clazz.getSuperclass().equals(Object.class)){\n interfaces.addAll(getAllInterfaces(clazz.getSuperclass()));\n }\n return interfaces ;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] |
116,593
|
<p>How do you clear the IRB console screen?</p>
|
[
{
"answer_id": 116603,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 6,
"selected": false,
"text": "%userprofile%\\.irbrc def cls\n system('cls')\nend\n"
},
{
"answer_id": 116614,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 6,
"selected": false,
"text": "`clear`\n system 'cls' # works\n`cls` # does not work\n system 'clear' # works\n`clear` # does not work\n"
},
{
"answer_id": 116812,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": -1,
"selected": false,
"text": "s = `cls`\nputs s\n"
},
{
"answer_id": 8402819,
"author": "TW Scannell",
"author_id": 1070767,
"author_profile": "https://Stackoverflow.com/users/1070767",
"pm_score": 4,
"selected": false,
"text": "clear => True ruby-1.9.2-p290 :007 > system 'clear'\n => true \nruby-1.9.2-p290 :007 > \n"
},
{
"answer_id": 9280225,
"author": "Sujit Kumar",
"author_id": 1209495,
"author_profile": "https://Stackoverflow.com/users/1209495",
"pm_score": 4,
"selected": false,
"text": "puts \"\\e[H\\e[2J\"\n"
},
{
"answer_id": 10291231,
"author": "Lucas Rockett Gutterman",
"author_id": 1352719,
"author_profile": "https://Stackoverflow.com/users/1352719",
"pm_score": 3,
"selected": false,
"text": "puts `clear`\n => nil"
},
{
"answer_id": 12100325,
"author": "accident-prone",
"author_id": 1621100,
"author_profile": "https://Stackoverflow.com/users/1621100",
"pm_score": 0,
"selected": false,
"text": "@echo off\ncls\n system('c')\n"
},
{
"answer_id": 12943393,
"author": "Marcos",
"author_id": 1069375,
"author_profile": "https://Stackoverflow.com/users/1069375",
"pm_score": 1,
"selected": false,
"text": "1.9.3-p125 :151 > system 'reset'\n"
},
{
"answer_id": 19467325,
"author": "orzFly",
"author_id": 2724079,
"author_profile": "https://Stackoverflow.com/users/2724079",
"pm_score": 0,
"selected": false,
"text": "->(a,b,c){x=a.method(b);a.send(c,b){send c,b,&x;false};print\"\\e[2J\\e[H \\e[D\"}[irb_context,:echo?,:define_singleton_method]\n lambda {\n original_echo = irb_context.method(:echo?)\n irb_context.send(:define_singleton_method, :echo?) {\n send :define_singleton_method, :echo?, &original_echo\n false\n }\n print \"\\e[2J\\e[H \\e[D\"\n}.call\n echo? \\e[2J \\e[H \\e[D"
},
{
"answer_id": 21165700,
"author": "Clay H",
"author_id": 2120317,
"author_profile": "https://Stackoverflow.com/users/2120317",
"pm_score": 3,
"selected": false,
"text": "system('cls')\n"
},
{
"answer_id": 24663366,
"author": "TheFed",
"author_id": 3361239,
"author_profile": "https://Stackoverflow.com/users/3361239",
"pm_score": 2,
"selected": false,
"text": "~/.irbrc def clear\n conf.return_format = \"\"\n system('clear')\nend\n Cntrl-L Cntrl-K"
},
{
"answer_id": 24797028,
"author": "Chandresh Pant",
"author_id": 713152,
"author_profile": "https://Stackoverflow.com/users/713152",
"pm_score": 4,
"selected": false,
"text": ". . clear\n . cls\n"
},
{
"answer_id": 26099640,
"author": "Lucky",
"author_id": 1793718,
"author_profile": "https://Stackoverflow.com/users/1793718",
"pm_score": 2,
"selected": false,
"text": "system 'cls'\n system('cls')\n irb(main):333:0> system 'cls'\nirb(main):007:0> system('cls')\n => nil system('clear')\nsystem 'clear'\nsystem `cls` #using the backquotes below ESC Key in windows\n"
},
{
"answer_id": 27045647,
"author": "avinashbot",
"author_id": 898577,
"author_profile": "https://Stackoverflow.com/users/898577",
"pm_score": 2,
"selected": false,
"text": "def clear\n system(\"cls\") || system(\"clear\") || puts(\"\\e[H\\e[2J\")\nend\n\nclear\n"
},
{
"answer_id": 32719924,
"author": "saadibabar",
"author_id": 5250192,
"author_profile": "https://Stackoverflow.com/users/5250192",
"pm_score": 2,
"selected": false,
"text": "system 'cls' \n"
},
{
"answer_id": 33233472,
"author": "Arvind singh",
"author_id": 956210,
"author_profile": "https://Stackoverflow.com/users/956210",
"pm_score": 4,
"selected": false,
"text": "system 'clear'\n"
},
{
"answer_id": 38531343,
"author": "Stephen Ross",
"author_id": 4297128,
"author_profile": "https://Stackoverflow.com/users/4297128",
"pm_score": 3,
"selected": false,
"text": "def clear_screen\n if RUBY_PLATFORM =~ /win32|win64|\\.NET|windows|cygwin|mingw32/i\n system('cls')\n else\n system('clear')\n end\nend system('clear')"
},
{
"answer_id": 39060089,
"author": "Eric Haynes",
"author_id": 1057157,
"author_profile": "https://Stackoverflow.com/users/1057157",
"pm_score": 2,
"selected": false,
"text": "def cls\n puts \"\\ec\\e[3J\"\nend\n\ndef clear\n puts \"\\e[H\\e[2Js\"\nend\n alias cls='echo -e \"\\ec\\e[3J\"'\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450/"
] |
116,626
|
<p>I'm trying to polish up my Ruby by re writing Kent Beck's xUnit Python example from "Test Driven Development: By Example". I've got quite far but now I get the following error when I run which I don't grok.</p>
<pre><code>C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `test_running': wrong number of arguments (0 for 2) (ArgumentError)
from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `run'
from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:85
</code></pre>
<p>My code looks like this:</p>
<pre><code>class TestCase
def initialize(name)
puts "1. inside TestCase.initialise: @name: #{name}"
@name = name
end
def set_up
# No implementation (but present to be overridden in WasRun)
end
def run
self.set_up
self.send @name # <<<<<<<<<<<<<<<<<<<<<<<<<= ERROR HERE!!!!!!
end
end
class WasRun < TestCase
attr_accessor :wasRun
attr_accessor :wasSetUp
def initialize(name)
super(name)
end
def set_up
@wasRun = false
@wasSetUp = true
end
def test_method
@wasRun = true
end
end
class TestCaseTest < TestCase
def set_up
@test = WasRun.new("test_method")
end
def test_running
@test.run
puts "test was run? (true expected): #{test.wasRun}"
end
def test_set_up
@test.run
puts "test was set up? (true expected): #{test.wasSetUp}"
end
end
TestCaseTest.new("test_running").run
</code></pre>
<p>Can anyone point out my obvious mistake?</p>
|
[
{
"answer_id": 116688,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 0,
"selected": false,
"text": "send puts \"test was run? (true expected): #{test.wasRun}\"\n puts \"test was run? (true expected): #{@test.wasRun}\"\n"
},
{
"answer_id": 117053,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 5,
"selected": true,
"text": " puts \"test was run? (true expected): #{test.wasRun}\"\n puts \"test was run? (true expected): #{@test.wasRun}\"\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
] |
116,635
|
<p>(I've asked the same question of the jmeter-user mailing list, but I wanted to try here as well - so at the least I can update this with the answer once I find it).</p>
<p>I'm having trouble using <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> to test a Tomcat webapp using a self-signed SSL cert. JMeter throws a SocketException with message <code>Unconnected sockets not implemented</code>. <a href="http://jakarta.apache.org/jmeter/usermanual/get-started.html#opt_ssl" rel="noreferrer">According to JMeter's docs</a>, the application is designed and written to accept any certificate, self-signed or CA signed or whatever.</p>
<p>Has anyone run into this specific exception before?</p>
<p>I've attempted to export this certificate from the server and import it into my local keystore (with <em>keytool -import -alias tomcat -file </em>), but the result is the same.</p>
<p>I've also tried setting javax.net.debug=all as a JVM arg (<a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/ReadDebug.html" rel="noreferrer">the JSSE reference guide</a> lists this as a debugging step); however, I don't see any debugging output anywhere - should I expect this somewhere other than standard out/error?</p>
|
[
{
"answer_id": 1868392,
"author": "Suppressingfire",
"author_id": 49922,
"author_profile": "https://Stackoverflow.com/users/49922",
"pm_score": 0,
"selected": false,
"text": "Security.setProperty(\"ssl.SocketFactory.provider\", \"com.ibm.jsse2.SSLSocketFactoryImpl\");\n Security.setProperty(\"ssl.SocketFactory.provider\", \"com.ibm.websphere.ssl.protocol.SSLSocketFactory\");\n ServerSocketFactory"
},
{
"answer_id": 6579665,
"author": "Dikla",
"author_id": 59241,
"author_profile": "https://Stackoverflow.com/users/59241",
"pm_score": 2,
"selected": false,
"text": "SocketFactory com.sun.jndi.ldap.Connection SocketFactory Method.invoke() createSocket()"
},
{
"answer_id": 27764501,
"author": "Flow",
"author_id": 194894,
"author_profile": "https://Stackoverflow.com/users/194894",
"pm_score": 4,
"selected": false,
"text": "javax.net.SocketFactory createSocket() createSocket() public Socket createSocket() throws IOException {\n throw new SocketException(\"Unconnected sockets not implemented\");\n}\n javax.net.SocketFactory createSocket() createSocket()"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
116,640
|
<p>I'm experiencing an issue on a test machine running Red Hat Linux (kernel version is 2.4.21-37.ELsmp) using Java 1.6 (1.6.0_02 or 1.6.0_04). The problem is, once a certain number of threads are created in a single thread group, the operating system is unwilling or unable to create any more.</p>
<p>This seems to be specific to Java creating threads, as the C thread-limit program was able to create about 1.5k threads. Additionally, this doesn't happen with a Java 1.4 JVM... it can create over 1.4k threads, though they are obviously being handled differently with respect to the OS.</p>
<p>In this case, the number of threads it's cutting off at is a mere 29 threads. This is testable with a simple Java program that just creates threads until it gets an error and then prints the number of threads it created. The error is a <pre>java.lang.OutOfMemoryError: unable to create new native thread</pre></p>
<p>This seems to be unaffected by things such as the number of threads in use by other processes or users or the total amount of memory the system is using at the time. JVM settings like Xms, Xmx, and Xss don't seem to change anything either (which is expected, considering the issue seems to be with native OS thread creation).</p>
<p>The output of "ulimit -a" is as follows:</p>
<pre>
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
file size (blocks, -f) unlimited
max locked memory (kbytes, -l) 4
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 7168
virtual memory (kbytes, -v) unlimited
</pre>
<p>The user process limit does not seem to be the issue. Searching for information on what could be wrong has not turned up much, but <a href="http://blogs.oracle.com/gverma/2008/03/redhat_linux_kernels_and_proce_1.html" rel="nofollow noreferrer">this post</a> seems to indicate that at least some Red Hat kernels limit a process to 300 MB of memory allocated for stack, and at 10 MB per thread for stack, it seems like the issue could be there (though it seems strange and unlikely as well).</p>
<p>I've tried changing the stack size with "ulimit -s" to test this, but any value other than 10240 and the JVM does not start with an error of:</p>
<pre>Error occurred during initialization of VM
Cannot create VM thread. Out of system resources.</pre>
<p>I can generally get around Linux, but I really don't know much about system configuration, and I haven't been able to find anything specifically addressing this kind of situation. Any ideas on what system or JVM settings could be causing this would be appreciated.</p>
<p><strong>Edits</strong>: Running the thread-limit program mentioned by <a href="https://stackoverflow.com/questions/116640/low-single-process-thread-limit-in-red-hat-linux#116696">plinth</a>, there was no failure until it tried to create the 1529th thread.</p>
<p>The issue also did not occur using a 1.4 JVM (does occur with 1.6.0_02 and 1.6.0_04 JVMs, can't test with a 1.5 JVM at the moment).</p>
<p>The code for the thread test I'm using is as follows:</p>
<pre><code>public class ThreadTest {
public static void main(String[] pArgs) throws Exception {
try {
// keep spawning new threads forever
while (true) {
new TestThread().start();
}
}
// when out of memory error is reached, print out the number of
// successful threads spawned and exit
catch ( OutOfMemoryError e ) {
System.out.println(TestThread.CREATE_COUNT);
System.exit(-1);
}
}
static class TestThread extends Thread {
private static int CREATE_COUNT = 0;
public TestThread() {
CREATE_COUNT++;
}
// make the thread wait for eternity after being spawned
public void run() {
try {
sleep(Integer.MAX_VALUE);
}
// even if there is an interruption, dont do anything
catch (InterruptedException e) {
}
}
}
}
</code></pre>
<p>If you run this with a 1.4 JVM it will hang when it can't create any more threads and require a kill -9 (at least it did for me).</p>
<p><strong>More Edit:</strong></p>
<p>It turns out that the system that is having the problem is using the LinuxThreads threading model while another system that works fine is using the NPTL model. </p>
|
[
{
"answer_id": 117678,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 0,
"selected": false,
"text": "dsm@localhost:~$ javac ThreadTest.java \ndsm@localhost:~$ java ThreadTest \n8113\ndsm@localhost:~$ java -version\njava version \"1.6.0_07\"\nJava(TM) SE Runtime Environment (build 1.6.0_07-b06)\nJava HotSpot(TM) Client VM (build 10.0-b23, mixed mode, sharing)\ndsm@localhost:~$ \n"
},
{
"answer_id": 39077766,
"author": "Umut Uzun",
"author_id": 4374102,
"author_profile": "https://Stackoverflow.com/users/4374102",
"pm_score": 0,
"selected": false,
"text": "/etc/security/limits.d/90-nproc.conf /etc/security/limits.conf ulimit -u"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13792/"
] |
116,650
|
<p>I am tasked with writing an authentication component for an open source <code>JAVA</code> app. We have an in-house authentication widget that uses <code>https</code>. I have some example <code>php</code> code that accesses the <code>widget</code> which uses <code>cURL</code> to handle the transfer. </p>
<p>My question is whether or not there is a port of <code>cURL</code> to <code>JAVA</code>, or better yet, what base package will get me close enough to handle the task? </p>
<p><strong>Update</strong>:</p>
<p>This is in a nutshell, the code I would like to replicate in JAVA:</p>
<pre><code>$cp = curl_init();
$my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&pt2=$pass&pt4=full";
curl_setopt($cp, CURLOPT_URL, $my_url);
curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($cp);
curl_close($cp);
</code></pre>
<p><a href="https://stackoverflow.com/questions/116650/curl-equivalent-in-java#116725">Heath</a>, I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.</p>
|
[
{
"answer_id": 116725,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 7,
"selected": true,
"text": "HttpURLConnection con = (HttpURLConnection) new URL(\"https://www.example.com\").openConnection();\ncon.setRequestMethod(\"POST\");\ncon.getOutputStream().write(\"LOGIN\".getBytes(\"UTF-8\"));\ncon.getInputStream();\n"
},
{
"answer_id": 22444271,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "Document doc = Jsoup.connect(\"http://en.wikipedia.org/\").get();\n"
},
{
"answer_id": 57321671,
"author": "jeffrey",
"author_id": 10594630,
"author_profile": "https://Stackoverflow.com/users/10594630",
"pm_score": 0,
"selected": false,
"text": "public Object curl(String url, Object postData, String method) {\n\nCurlLib curl = CurlFactory.getInstance(\"default\");\nch = curl.curl_init();\ncurl.curl_setopt(ch, CurlOption.CURLOPT_CONNECTTIMEOUT, 1000);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_TIMEOUT, 5000);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYPEER, false);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_SSL_VERIFYHOST, false);\nString postDataStr = \"key1=v1\";\n\ncurl.curl_setopt(ch, CurlOption.CURLOPT_CUSTOMREQUEST, \"POST\");\ncurl.curl_setopt(ch, CurlOption.CURLOPT_POSTFIELDS, postDataStr);\ncurl.curl_setopt(ch, CurlOption.CURLOPT_URL, \"https://xxxx.com/yyy\");\nObject html = curl.curl_exec(ch);\nObject httpCode = curl.curl_getinfo(ch, CurlInfo.CURLINFO_HTTP_CODE);\nif (httpCode != null && 200 == Integer.valueOf(httpCode.toString())) {\n return null;\n}\nreturn html;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16253/"
] |
116,654
|
<p>C++ is probably the most popular language for <a href="https://stackoverflow.com/questions/112277/best-intro-to-c-static-metaprogramming">static metaprogramming</a> and <a href="https://stackoverflow.com/questions/112320/is-static-metaprogramming-possible-in-java">Java doesn't support it</a>.</p>
<p>Are there any other languages besides C++ that support generative programming (programs that create programs)?</p>
|
[
{
"answer_id": 122596,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 3,
"selected": false,
"text": "defmacro"
},
{
"answer_id": 63435262,
"author": "Dmitry Ponyatov",
"author_id": 2134384,
"author_profile": "https://Stackoverflow.com/users/2134384",
"pm_score": 0,
"selected": false,
"text": "# from metaL import *\nclass Object:\n def __init__(self, V):\n self.val = V\n self.slot = {}\n self.nest = []\n\n\nclass Module(Object):\n def cc(self):\n c = '// \\ %s\\n' % self.head(test=True)\n for i in self.nest:\n c += i.cc()\n c += '// / %s\\n' % self.head(test=True)\n return c\n\nhello = Module('hello')\n\n# <module:hello> #a04475a2\n\nclass Include(Object):\n def cc(self):\n return '#include <%s.h>\\n' % self.val\n\nstdlib = Include('stdlib')\nhello // stdlib\n\n# <module:hello> #b6efb657\n# 0: <include:stdlib> #f1af3e21\n\nclass Fn(Object):\n def cc(self):\n return '\\nvoid %s() {\\n}\\n\\n' % self.val\n\nmain = Fn('main')\nhello // main\n\nprint(hello.cc())\n // \\ <module:hello>\n#include <stdlib.h>\n\nvoid main() {\n}\n\n// / <module:hello>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
116,682
|
<p>I have a URI here in which a simple document.cookie query through the console is resulting in three cookies being displayed. I verified this with trivial code such as the following as well:</p>
<pre><code>var cookies = document.cookie.split(';');
console.log(cookies.length);
</code></pre>
<p>The variable cookies does indeed come out to the number 3. Web Developer on the other hand is indicating that a grand total of 8 cookies are in use.</p>
<p>I'm slightly confused to believe which is inaccurate. I believe the best solution might involve just reiterating the code above without the influence of Firebug. However, I was wondering if someone might suggest a more clever alternative to decipher which tool is giving me the inaccurate information.</p>
|
[
{
"answer_id": 122596,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 3,
"selected": false,
"text": "defmacro"
},
{
"answer_id": 63435262,
"author": "Dmitry Ponyatov",
"author_id": 2134384,
"author_profile": "https://Stackoverflow.com/users/2134384",
"pm_score": 0,
"selected": false,
"text": "# from metaL import *\nclass Object:\n def __init__(self, V):\n self.val = V\n self.slot = {}\n self.nest = []\n\n\nclass Module(Object):\n def cc(self):\n c = '// \\ %s\\n' % self.head(test=True)\n for i in self.nest:\n c += i.cc()\n c += '// / %s\\n' % self.head(test=True)\n return c\n\nhello = Module('hello')\n\n# <module:hello> #a04475a2\n\nclass Include(Object):\n def cc(self):\n return '#include <%s.h>\\n' % self.val\n\nstdlib = Include('stdlib')\nhello // stdlib\n\n# <module:hello> #b6efb657\n# 0: <include:stdlib> #f1af3e21\n\nclass Fn(Object):\n def cc(self):\n return '\\nvoid %s() {\\n}\\n\\n' % self.val\n\nmain = Fn('main')\nhello // main\n\nprint(hello.cc())\n // \\ <module:hello>\n#include <stdlib.h>\n\nvoid main() {\n}\n\n// / <module:hello>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
116,684
|
<p>Is there <em>anything</em> available that isn't trivially breakable?</p>
|
[
{
"answer_id": 116767,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "[update, now they are] [update, now it is very easy to break] [update, pretty easy up to 9 char passwords now] [You can now rent this 'Cray' from Amazon]"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
] |
116,687
|
<p>I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below.</p>
<p>(I'm completely new to C++, I come from a Java background and I'm a little familiar with C.)</p>
<pre><code>// CppClass.cpp
#include <iostream>
#include <pthread.h>
static pthread_t thread;
static pthread_mutex_t mutex;
static pthread_cond_t cond;
static int shutdown;
using namespace std;
class CppClass
{
public:
static void Start()
{
cout << "Testing start function." << endl;
shutdown = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread, &attr, run_thread, NULL);
}
static void Stop()
{
pthread_mutex_lock(&mutex);
shutdown = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
static void Join()
{
pthread_join(thread, NULL);
}
private:
static void *run_thread(void *pthread_args)
{
CppClass *obj = new CppClass();
pthread_mutex_lock(&mutex);
while (shutdown == 0)
{
struct timespec ts;
ts.tv_sec = time(NULL) + 3;
pthread_cond_timedwait(&cond, &mutex, &ts);
if (shutdown)
{
break;
}
obj->display();
}
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return NULL;
}
void display()
{
cout << " Inside display() " << endl;
}
};
// main.cpp
#include <iostream>
/*
* If I remove the comment below and delete the
* the class declaration part, it works.
*/
// #include "CppClass.cpp"
using namespace std;
class CppClass
{
public:
static void Start();
static void Stop();
static void Join();
};
int main()
{
CppClass::Start();
while (1)
{
int quit;
cout << "Do you want to end?: (0 = stay, 1 = quit) ";
cin >> quit;
cout << "Input: " << quit << endl;
if (quit)
{
CppClass::Stop();
cout << "Joining CppClass..." << endl;
CppClass::Join();
break;
}
}
}
</code></pre>
<p>When I tried to compile, I get the following error:</p>
<pre>
$ g++ -o go main.cpp CppClass.cpp -l pthread
/tmp/cclhBttM.o(.text+0x119): In function `main':
: undefined reference to `CppClass::Start()'
/tmp/cclhBttM.o(.text+0x182): In function `main':
: undefined reference to `CppClass::Stop()'
/tmp/cclhBttM.o(.text+0x1ad): In function `main':
: undefined reference to `CppClass::Join()'
collect2: ld returned 1 exit status
</pre>
<p>But if I remove the class declaration in main.cpp and replace it with #include "CppClass.cpp", it works fine. Basically, I want to put these declarations in a separate .h file and use it. Am I missing something?</p>
<p>Thanks for the help.</p>
|
[
{
"answer_id": 116741,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 6,
"selected": true,
"text": "class NewClass {\npublic:\n NewClass();\n int methodA();\n int methodB();\n}; <- don't forget the semicolon\n #include \"NewClass.h\"\n\nNewClass::NewClass() {\n // constructor goes here\n}\n\nint NewClass::methodA() {\n // methodA goes here\n return 0;\n}\n\nint NewClass::methodB() {\n // methodB goes here\n return 1;\n}\n #include \"NewClass.h\"\n\nint main() {\n NewClass nc;\n // do something with nc\n}\n"
},
{
"answer_id": 116878,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 3,
"selected": false,
"text": "// CppClass.h\nusing namespace std;\n\nclass CppClass\n{\npublic:\n static void Start();\n static void Stop();\n static void Join();\nprivate:\n void *run_thread(void *pthread_args);\n void display();\n};\n // CppClass.cpp\n#include <iostream>\n#include <pthread.h>\n#include \"CppClass.h\"\n\nusing namespace std;\n\nvoid CppClass::Start()\n{\n /* method body goes here */\n}\nvoid CppClass::Stop()\n{\n /* method body goes here */\n}\nvoid CppClass::Join()\n{\n /* method body goes here */\n}\nvoid *CppClass::run_thread(void *pthread_args)\n{\n /* method body goes here */\n}\nvoid CppClass::display() {\n /* method body goes here */\n}\n // main.cpp\n#include \"CppClass.h\"\n\nint main()\n{\n /* main method body here */\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
] |
116,690
|
<p>SVN keyword substition gives is not pretty. E.g.,</p>
<blockquote>
<p>Last updated: $Date$ by $Author$</p>
</blockquote>
<p>yields</p>
<blockquote>
<p>Last updated: $Date: 2008-09-22
14:38:43 -0400 (Mon, 22 Sep 2008) $ by
$Author: cconway $"</p>
</blockquote>
<p>Does anybody have a Javascript snippet that prettifies things and outputs some HTML? The result should be more like:</p>
<blockquote>
<p>Last update: 22 Sep 2008 by cconway</p>
</blockquote>
<p>P.S. Is there a way to replace "cconway" with a display name?</p>
|
[
{
"answer_id": 116804,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 2,
"selected": false,
"text": "function formatSvnString(string){\n var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n var re = /\\$Date: (\\d{4})-(\\d\\d)-(\\d\\d).*?\\$Author: (\\S+) \\$/\n return string.replace(re, function(match, year, month, day, author){ \n var date = new Date([year, month, day].join('/'))\n return date.getDate()\n + ' ' + months[date.getMonth()]\n + ' ' + date.getFullYear()\n + ' by ' + author\n })\n}\n formatSvnString(\"$Date: 2008-09-22 14:38:43 -0400 (Mon, 22 Sep 2008) $ by $Author: cconway $\")\n// returns: 22 Sep 2008 by cconway\n"
},
{
"answer_id": 127785,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 0,
"selected": false,
"text": "<div class=\"timestamp\" />"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
116,701
|
<p>What's the best way for a running C or C++ program that's been launched from the command line to put itself into the background, equivalent to if the user had launched from the unix shell with '&' at the end of the command? (But the user didn't.) It's a GUI app and doesn't need any shell I/O, so there's no reason to tie up the shell after launch. But I want a shell command launch to be auto-backgrounded without the '&' (or on Windows).</p>
<p>Ideally, I want a solution that would work on any of Linux, OS X, and Windows. (Or separate solutions that I can select with #ifdef.) It's ok to assume that this should be done right at the beginning of execution, as opposed to somewhere in the middle.</p>
<p>One solution is to have the main program be a script that launches the real binary, carefully putting it into the background. But it seems unsatisfying to need these coupled shell/binary pairs.</p>
<p>Another solution is to immediately launch <em>another</em> executed version (with 'system' or CreateProcess), with the same command line arguments, but putting the child in the background and then having the parent exit. But this seems clunky compared to the process putting <em>itself</em> into background.</p>
<p><strong>Edited after a few answers</strong>: Yes, a fork() (or system(), or CreateProcess on Windows) is one way to sort of do this, that I hinted at in my original question. But all of these solutions make a SECOND process that is backgrounded, and then terminate the original process. I was wondering if there was a way to put the EXISTING process into the background. One difference is that if the app was launched from a script that recorded its process id (perhaps for later killing or other purpose), the newly forked or created process will have a different id and so will not be controllable by any launching script, if you see what I'm getting at.</p>
<p><strong>Edit #2</strong>: </p>
<p>fork() isn't a good solution for OS X, where the man page for 'fork' says that it's unsafe if certain frameworks or libraries are being used. I tried it, and my app complains loudly at runtime: "The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec()." </p>
<p>I was intrigued by daemon(), but when I tried it on OS X, it gave the same error message, so I assume that it's just a fancy wrapper for fork() and has the same restrictions.</p>
<p>Excuse the OS X centrism, it just happens to be the system in front of me at the moment. But I am indeed looking for a solution to all three platforms.</p>
|
[
{
"answer_id": 116813,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "fork() setsid()"
},
{
"answer_id": 116814,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 3,
"selected": false,
"text": "fork\nsetsid\nredirect STDIN, STDOUT and STDERR to /dev/null\n"
},
{
"answer_id": 116833,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": 0,
"selected": false,
"text": "STD{OUT,ERR} return pid; main()"
},
{
"answer_id": 116838,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 1,
"selected": false,
"text": "if (fork() != 0) exit(0);\n 0 1 2 if (fork() != 0) exit(0); setpgroup(0,getpid()); /* Might be necessary to prevent a SIGHUP on shell exit. */ signal(SIGHUP,SIG_IGN); /* just in case, same as using nohup to launch program. */ fd=open(\"/dev/tty\",O_RDWR); ioctl(fd,TIOCNOTTY,0); /* Disassociates from the terminal */ close(fd); if (fork() != 0) exit(0); /* just for good measure */"
},
{
"answer_id": 116891,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 2,
"selected": false,
"text": "initialization_code()\nif(failure) exit(1)\nif( fork() > 0 ) exit(0)\nsetsid()\nsetup_signal_handlers()\nfor(fd=0; fd<NOFILE; fd++) close(fd)\nopen(\"/dev/null\", O_RDONLY)\nopen(\"/dev/null\", O_WRONLY)\nopen(\"/dev/null\", o_WRONLY)\nchdir(\"/\")\n"
},
{
"answer_id": 116941,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "#! /bin/sh\n/path/to/myGuiApplication &\n"
},
{
"answer_id": 118081,
"author": "Rodrigo Queiro",
"author_id": 20330,
"author_profile": "https://Stackoverflow.com/users/20330",
"pm_score": 0,
"selected": false,
"text": "#include stdio.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <CoreFoundation/CoreFoundation.h>\n\nint main(int argc, char **argv)\n{\n int i, j;\n\n for (i=1; i<argc; i++)\n if (strcmp(argv[i], \"--daemon\") == 0)\n {\n for (j = i+1; j<argc; j++)\n argv[j-1] = argv[j];\n\n argv[argc - 1] = NULL;\n\n if (fork()) return 0;\n\n execv(argv[0], argv);\n\n return 0;\n }\n\n\n sleep(1);\n\n CFRunLoopRun();\n\n CFStringRef hello = CFSTR(\"Hello, world!\");\n\n printf(\"str: %s\\n\", CFStringGetCStringPtr(hello, CFStringGetFastestEncoding(hello)));\n\n return 0;\n}\n"
},
{
"answer_id": 118360,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 4,
"selected": false,
"text": "gui-program &\npid=$!\n# do something with $pid later, such as check if the program is still running\n"
},
{
"answer_id": 327579,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/**Deamonize*/\n\npid_t pid;\npid = fork(); /**father makes a little deamon(son)*/\nif(pid>0)\nexit(0); /**father dies*/\nwhile(1){\nprintf(\"Hello I'm your little deamon %d\\n\",pid); /**The child deamon goes on*/\nsleep(1)\n}\n\n/** try 'nohup' in linux(usage: nohup <command> &) */\n"
},
{
"answer_id": 577482,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "fork() fork"
},
{
"answer_id": 2506801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "_exit(0); exit(0); _exit(0);"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3832/"
] |
116,760
|
<p>I have a rather weak understanding of any of oracle's more advanced functionality but this should I think be possible.</p>
<p>Say I have a table with the following schema:</p>
<pre><code>MyTable
Id INTEGER,
Col1 VARCHAR2(100),
Col2 VARCHAR2(100)
</code></pre>
<p>I would like to write an sproc with the following </p>
<pre><code>PROCEDURE InsertOrUpdateMyTable(p_id in integer, p_col1 in varcahr2, p_col2 in varchar2)
</code></pre>
<p>Which, in the case of an update will, if the value in p_col1, p_col2 is null will not overwrite Col1, Col2 respectively</p>
<p>So If I have a record:</p>
<pre><code>id=123, Col1='ABC', Col2='DEF'
exec InsertOrUpdateMyTable(123, 'XYZ', '098'); --results in id=123, Col1='XYZ', Col2='098'
exec InsertOrUpdateMyTable(123, NULL, '098'); --results in id=123, Col1='ABC', Col2='098'
exec InsertOrUpdateMyTable(123, NULL, NULL); --results in id=123, Col1='ABC', Col2='DEF'
</code></pre>
<p>Is there any simple way of doing this without having multiple SQL statements? </p>
<p>I am thinking there might be a way to do this with the Merge statement though I am only mildly familiar with it.</p>
<hr>
<p><strong>EDIT:</strong>
Cade Roux bellow suggests using COALESCE which works great! <a href="http://www.java2s.com/Code/Oracle/Conversion-Functions/COALESCEreturnsthefirstnonnullexpressionintheexpressionlist.htm" rel="nofollow noreferrer">Here are some examples of using the coalesce kewyord.</a>
And here is the solution for my problem:</p>
<pre><code>MERGE INTO MyTable mt
USING (SELECT 1 FROM DUAL) a
ON (mt.ID = p_id)
WHEN MATCHED THEN
UPDATE
SET mt.Col1 = coalesce(p_col1, mt.Col1), mt.Col2 = coalesce(p_col2, mt.Col2)
WHEN NOT MATCHED THEN
INSERT (ID, Col1, Col2)
VALUES (p_id, p_col1, p_col2);
</code></pre>
|
[
{
"answer_id": 116795,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": true,
"text": "SET a.Col1 = COALESCE(incoming.Col1, a.Col1)\n ,a.Col2 = COALESCE(incoming.Col2, a.Col2)\n"
},
{
"answer_id": 116796,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": "nvl(newValue, oldValue)\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
116,775
|
<p>I am adding custom controls to a FlowLayoutPanel. Each control has a date property. I would like to sort the controls in the flowlayoutpanel based on the date property. I can't presort the controls before I add them because it is possible for the user to add more.</p>
<p>My current thought is when the ControlAdded event for the FlowLayoutPanel is triggered I loop through the controls and use the BringToFront function to order the controls based on the date. </p>
<p>What is the best way to do this?</p>
|
[
{
"answer_id": 117766,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 3,
"selected": true,
"text": " SortedList<DateTime,Control> sl = new SortedList<DateTime,Control>();\n foreach (Control i in mainContent.Controls)\n {\n if (i.GetType().BaseType == typeof(MyBaseType))\n {\n MyBaseType iTyped = (MyBaseType)i;\n sl.Add(iTyped.Date, iTyped);\n }\n }\n\n\n foreach (MyBaseType j in sl.Values)\n {\n j.SendToBack();\n }\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
116,797
|
<p>I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax:</p>
<pre><code><uc1:mycontrol runat="server" myintarray="1,2,3" />
</code></pre>
<p>This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make <code>myintarray</code> a string and parse it in the setter, but I was wondering if there was a more elegant solution.</p>
|
[
{
"answer_id": 116953,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": 3,
"selected": false,
"text": "asp: <uc1:mycontrol runat=\"server\">\n <uc1:myintparam>1</uc1:myintparam>\n <uc1:myintparam>2</uc1:myintparam>\n <uc1:myintparam>3</uc1:myintparam>\n</uc1:mycontrol>\n"
},
{
"answer_id": 117027,
"author": "user19264",
"author_id": 19264,
"author_profile": "https://Stackoverflow.com/users/19264",
"pm_score": 0,
"selected": false,
"text": "<script runat=\"server\">\nprotected void Page_Load(object sender, EventArgs e)\n{\n YourUserControlID.myintarray = new Int32[] { 1, 2, 3 };\n}\n</script>\n"
},
{
"answer_id": 117054,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "[ParseChildren(true, \"Actions\")]\n[PersistChildren(false)]\n[ToolboxData(\"<{0}:PageActionManager runat=\\\"server\\\" ></PageActionManager>\")]\n[NonVisualControl]\npublic class PageActionManager : Control\n{\n private ArrayList _actions = new ArrayList();\n public ArrayList Actions\n {\n get\n {\n return _actions;\n }\n }\n"
},
{
"answer_id": 117122,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 5,
"selected": true,
"text": "public class IntArrayConverter : System.ComponentModel.TypeConverter\n{\n public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)\n {\n return sourceType == typeof(string);\n }\n public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)\n {\n string val = value as string;\n string[] vals = val.Split(',');\n System.Collections.Generic.List<int> ints = new System.Collections.Generic.List<int>();\n foreach (string s in vals)\n ints.Add(Convert.ToInt32(s));\n return ints.ToArray();\n }\n}\n private int[] ints;\n[TypeConverter(typeof(IntsConverter))]\npublic int[] Ints\n{\n get { return this.ints; }\n set { this.ints = value; }\n}\n"
},
{
"answer_id": 117522,
"author": "ern",
"author_id": 5609,
"author_profile": "https://Stackoverflow.com/users/5609",
"pm_score": 3,
"selected": false,
"text": "public class IntArrayConverter : System.ComponentModel.TypeConverter\n{\n public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)\n {\n return sourceType == typeof(string);\n }\n public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)\n {\n string val = value as string;\n string[] vals = val.Split(',');\n System.Collections.Generic.List<int> ints = new System.Collections.Generic.List<int>();\n foreach (string s in vals)\n ints.Add(Convert.ToInt32(s));\n return ints.ToArray();\n }\n}\n"
},
{
"answer_id": 1782648,
"author": "Dgc",
"author_id": 216960,
"author_profile": "https://Stackoverflow.com/users/216960",
"pm_score": 2,
"selected": false,
"text": "namespace InternalArray\n{\n /// <summary>\n /// Item for setting value specifically\n /// </summary>\n\n public class ArrayItem\n {\n public int Value { get; set; }\n }\n\n public class CustomUserControl : UserControl\n {\n\n private List<int> Ints {get {return this.ItemsToList();}\n /// <summary>\n /// set our values explicitly\n /// </summary>\n [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(List<ArrayItem>))]\n public List<ArrayItem> Values { get; set; }\n\n /// <summary>\n /// Converts our ArrayItem into a List<int> \n /// </summary>\n /// <returns></returns>\n private List<int> ItemsToList()\n {\n return (from q in this.Values\n select q.Value).ToList<int>();\n }\n }\n}\n <xx:CustomUserControl runat=\"server\">\n <Values>\n <xx:ArrayItem Value=\"1\" />\n </Values>\n</xx:CustomUserControl>\n"
},
{
"answer_id": 9399322,
"author": "spleenboy",
"author_id": 1226421,
"author_profile": "https://Stackoverflow.com/users/1226421",
"pm_score": 2,
"selected": false,
"text": "public class ArrayConverter<T> : TypeConverter\n{\n public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n {\n return sourceType == typeof(string);\n }\n\n public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)\n {\n string val = value as string;\n if (string.IsNullOrEmpty(val))\n return new T[0];\n\n string[] vals = val.Split(',');\n List<T> items = new List<T>();\n Type type = typeof(T);\n foreach (string s in vals)\n {\n T item = (T)Convert.ChangeType(s, type);\n items.Add(item);\n }\n return items.ToArray();\n }\n}\n [TypeConverter(typeof(ArrayConverter<int>))]\npublic int[] Ints { get; set; }\n\n[TypeConverter(typeof(ArrayConverter<long>))]\npublic long[] Longs { get; set; }\n\n[TypeConverter(typeof(ArrayConverter<DateTime))]\npublic DateTime[] DateTimes { get; set; }\n"
},
{
"answer_id": 63563015,
"author": "Protector one",
"author_id": 125938,
"author_profile": "https://Stackoverflow.com/users/125938",
"pm_score": 0,
"selected": false,
"text": "<uc1:mycontrol runat=\"server\" myintarray=\"<%# new [] {1, 2, 3} %>\" />\n [ExpressionPrefix(\"Code\")]\npublic class CodeExpressionBuilder : ExpressionBuilder\n{\n public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)\n {\n return new CodeSnippetExpression(entry.Expression.Trim());\n }\n}\n <uc1:mycontrol runat=\"server\" myintarray=\"<%$ Code: new [] {1, 2, 3} %>\" />\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5609/"
] |
116,810
|
<p>I'm auditing our existing web application, which makes heavy use of <a href="http://www.w3schools.com/HTML/html_frames.asp" rel="nofollow noreferrer">HTML frames</a>. I would like to download all of the HTML in each frame, is there a method of doing this with <a href="http://www.gnu.org/software/wget/" rel="nofollow noreferrer">wget</a> or a little bit of scripting?</p>
|
[
{
"answer_id": 116849,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "wget --recursive --domains=www.mysite.com http://www.mysite.com\n"
},
{
"answer_id": 116863,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 4,
"selected": true,
"text": " wget -rH -Dserver.com http://www.server.com/\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302/"
] |
116,819
|
<p>I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords.</p>
|
[
{
"answer_id": 116862,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 4,
"selected": false,
"text": "\\b(boon\\.ini|http)\\b\n true \\b \\b(boon\\.ini|http|foo|bar)\\b\n"
},
{
"answer_id": 116864,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": 7,
"selected": true,
"text": "^(?:(?!boon\\.ini|http).)*$\\r?\\n?\n"
},
{
"answer_id": 116883,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "if (!/boon\\.ini|http/) {\n # the string passed!\n}\n"
},
{
"answer_id": 116964,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 1,
"selected": false,
"text": "(?...)"
},
{
"answer_id": 831989,
"author": "Tim",
"author_id": 102510,
"author_profile": "https://Stackoverflow.com/users/102510",
"pm_score": 4,
"selected": false,
"text": "^(?!.*IgnoreMe).*$\n ^ $ (?! Expression) ^ (?!.*IgnoreMe).*$\n"
},
{
"answer_id": 2798285,
"author": "Manikandan",
"author_id": 336704,
"author_profile": "https://Stackoverflow.com/users/336704",
"pm_score": 2,
"selected": false,
"text": "^[^£]*$\n"
},
{
"answer_id": 19641987,
"author": "Jon Kern",
"author_id": 344720,
"author_profile": "https://Stackoverflow.com/users/344720",
"pm_score": 0,
"selected": false,
"text": "^\\w+-*\\w*\\.(?!(?:alpha(123)*\\.|beta(123)*\\.|preprod\\.)domain\\.com).*$\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19161/"
] |
116,824
|
<p>Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing</p>
<pre><code>$result = mysql_query("SELECT id FROM table");
$total = mysql_num_rows($result)
</code></pre>
<p>I was told this was not very efficient or fast, if you have a lot of records in the table. </p>
|
[
{
"answer_id": 116829,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "$result = mysql_query(\"SELECT COUNT(id) FROM table\");\n"
},
{
"answer_id": 116840,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 6,
"selected": true,
"text": "$result = mysql_query( \"select count(id) as num_rows from table\" );\n$row = mysql_fetch_object( $result );\n$total = $row->num_rows;\n"
},
{
"answer_id": 116858,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$result = mysql_query(\"SELECT COUNT(id) AS total_things from table\");\n$row = mysql_fetch_array($result,MYSQL_ASSOC);\n$num_results = $row[\"total_things\"];\n"
},
{
"answer_id": 116867,
"author": "VoxPelli",
"author_id": 20667,
"author_profile": "https://Stackoverflow.com/users/20667",
"pm_score": 2,
"selected": false,
"text": "$result = mysql_query(\"SELECT COUNT(*) FROM table\");\n"
},
{
"answer_id": 117315,
"author": "skoob",
"author_id": 20708,
"author_profile": "https://Stackoverflow.com/users/20708",
"pm_score": 2,
"selected": false,
"text": "SELECT COUNT(*) FROM table\n"
},
{
"answer_id": 187759,
"author": "Annika Backstrom",
"author_id": 7675,
"author_profile": "https://Stackoverflow.com/users/7675",
"pm_score": 0,
"selected": false,
"text": "SHOW TABLE STATUS Rows"
},
{
"answer_id": 34766624,
"author": "Divakarcool",
"author_id": 3797574,
"author_profile": "https://Stackoverflow.com/users/3797574",
"pm_score": 0,
"selected": false,
"text": "$num= mysql_query(\"SELECT COUNT(id) FROM $table\");\n"
},
{
"answer_id": 43727050,
"author": "Apostolos",
"author_id": 5615873,
"author_profile": "https://Stackoverflow.com/users/5615873",
"pm_score": 0,
"selected": false,
"text": "$result = $dbh->query(\"SELECT id FROM {table_name}\");\n$total = $result->num_rows;\n $result = $dbh->query(\"SELECT id FROM {table_name}\");\n$total = $result->rowCount();\n"
},
{
"answer_id": 68963111,
"author": "kurdtpage",
"author_id": 600852,
"author_profile": "https://Stackoverflow.com/users/600852",
"pm_score": 0,
"selected": false,
"text": "SELECT TABLE_NAME, TABLE_ROWS\nFROM information_schema.tables\nWHERE TABLE_SCHEMA = \"database\";\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
116,830
|
<p>In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this:</p>
<pre><code>Foo<?> x;
</code></pre>
<p>Is there an equivalent construct to this question-mark, in C#?</p>
|
[
{
"answer_id": 116881,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": false,
"text": "class Foo\n{\n}\n\nclass Foo<T> : Foo\n{\n}\n Foo t = new Foo<int>();\n"
},
{
"answer_id": 116948,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 6,
"selected": true,
"text": "using System;\nusing System.Collections;\nusing System.Collections.Generic; \n\nclass Test{\n\n //Prints the contents of any generic Stack by \n //using generic type inference \n public static void PrintStackContents<T>(Stack<T> s){\n while(s.Count != 0){\n Console.WriteLine(s.Pop()); \n } \n }\n\n public static void Main(String[] args){\n\n Stack<int> s2 = new Stack<int>(); \n s2.Push(4); \n s2.Push(5); \n s2.Push(6); \n\n PrintStackContents(s2); \n\n Stack<string> s1 = new Stack<string>(); \n s1.Push(\"One\"); \n s1.Push(\"Two\"); \n s1.Push(\"Three\"); \n\n PrintStackContents(s1); \n }\n}\n import java.util.*; \n\nclass Test{\n\n //Prints the contents of any generic Stack by \n //specifying wildcard type \n public static void PrintStackContents(Stack<?> s){\n while(!s.empty()){\n System.out.println(s.pop()); \n }\n }\n\n public static void main(String[] args){\n\n Stack <Integer> s2 = new Stack <Integer>(); \n s2.push(4); \n s2.push(5); \n s2.push(6); \n\n PrintStackContents(s2); \n\n Stack<String> s1 = new Stack<String>(); \n s1.push(\"One\"); \n s1.push(\"Two\"); \n s1.push(\"Three\"); \n\n PrintStackContents(s1); \n }\n}\n"
},
{
"answer_id": 117000,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 3,
"selected": false,
"text": "interface IFoo<T>\n{\n T Bar(T t, int n);\n}\n Type IFoo<int> typeof(IFoo<int>) Type IFoo<T> typeof(IFoo<>) IFoo<T> T T Type theInterface = typeof(IFoo<>);\nType theSpecificInterface = theInterface.MakeGenericType(typeof(string));\n\n// theSpecificInterface now holds IFoo<string> even though we may not have known we wanted to use string until runtime\n\n// proceed with reflection as normal, make late bound calls / constructions, emit DynamicMethod code, etc.\n"
},
{
"answer_id": 11358440,
"author": "Dani",
"author_id": 785529,
"author_profile": "https://Stackoverflow.com/users/785529",
"pm_score": 4,
"selected": false,
"text": "Foo<object> x"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14113/"
] |
116,854
|
<p>I'm starting work on a project using Rails, but I'm waiting for the 3rd edition of the pragmatic rails book to come out before I purchase a book.</p>
<p>Anyway, my question is a bit more pointed than how do I get started...</p>
<p>What are some of the must have gems that everyone uses?</p>
<p>I need basic authentication, so I have the restful authentication gem, but beyond that, I don't know what I don't know. Is there a run down of this information somewhere? Some basic setup that 99% of the people start with when starting a new rails application?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 118880,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "||="
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
] |
116,869
|
<p>I know this is a dumb question. For some reason my mind is blank on this. Any ideas?</p>
<p>Sorry should have been more clear. </p>
<p>Using a <code>HtmlGenericControl</code> to pull in link description as well as image. </p>
<pre><code> private void InternalCreateChildControls()
{
if (this.DataItem != null && this.Relationships.Count > 0)
{
HtmlGenericControl fieldset = new HtmlGenericControl("fieldset");
this.Controls.Add(fieldset);
HtmlGenericControl legend = new HtmlGenericControl("legend");
legend.InnerText = this.Caption;
fieldset.Controls.Add(legend);
HtmlGenericControl listControl = new HtmlGenericControl("ul");
fieldset.Controls.Add(listControl);
for (int i = 0; i < this.Relationships.Count; i++)
{
CatalogRelationshipsDataSet.CatalogRelationship relationship =
this.Relationships[i];
HtmlGenericControl listItem = new HtmlGenericControl("li");
listControl.Controls.Add(listItem);
RelatedItemsContainer container = new RelatedItemsContainer(relationship);
listItem.Controls.Add(container);
Image Image = new Image();
Image.ImageUrl = relationship.DisplayName;
LinkButton link = new LinkButton();
link.Text = relationship.DisplayName;
///ToDO Add Image or Image and description
link.CommandName = "Redirect";
container.Controls.Add(link);
}
}
}
</code></pre>
<p></p>
<p><strong>Not asking anyone to do this for me just a reference or an idea.</strong> </p>
<p>Thanks -overly frustrated and feeling humbled.</p>
|
[
{
"answer_id": 116929,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "using System;\nusing System.Web;\n\nnamespace Example\n{ \n public class GetImage : IHttpHandler\n {\n\n public void ProcessRequest(HttpContext context)\n {\n if (context.Request.QueryString(\"id\") != null)\n {\n // Code that uses System.Drawing to construct the image\n // ...\n context.Response.ContentType = \"image/pjpeg\";\n context.Response.BinaryWrite(Image);\n context.Response.End();\n }\n }\n\n public bool IsReusable\n {\n get\n {\n return false;\n }\n }\n }\n}\n <img src=\"GetImage.ashx?id=111\"/>\n using System;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace Example.WebControl\n{\n\n [ToolboxData(\"<{0}:DynamicImageCreator runat=server></{0}:DynamicImageCreator>\")]\n public class DynamicImageCreator : Control\n {\n\n public int Id\n {\n get\n {\n if (ViewState[\"Id\" + this.ID] == null)\n return 0;\n else\n return ViewState[\"Id\"];\n }\n set\n {\n ViewState[\"Id\" + this.ID] = value;\n }\n }\n\n protected override void RenderContents(HtmlTextWriter output)\n {\n output.Write(\"<img src='getImage.ashx?id=\" + this.Id + \"'/>\");\n base.RenderContents(output);\n }\n }\n}\n <cc:DDynamicImageCreator id=\"db1\" Id=\"123\" runat=\"server/>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7911/"
] |
116,876
|
<p>I'm trying to build a Windows installer using Nullsoft Install System that requires installation by an Administrator. The installer makes a "logs" directory. Since regular users can run this application, that directory needs to be writable by regular users. How do I specify that all users should have permission to have write access to that directory in the NSIS script language?</p>
<p>I admit that this sounds a like a sort of bad idea, but the application is just an internal app used by only a few people on a private network. I just need the log files saved so that I can see why the app is broken if something bad happens. The users can't be made administrator.</p>
|
[
{
"answer_id": 116914,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "cacls xcacls"
},
{
"answer_id": 117088,
"author": "Jay R.",
"author_id": 5074,
"author_profile": "https://Stackoverflow.com/users/5074",
"pm_score": 6,
"selected": true,
"text": "AccessControl::GrantOnFile \"$INSTDIR\\logs\" \"(BU)\" \"FullAccess\"\n"
},
{
"answer_id": 3925642,
"author": "user474708",
"author_id": 474708,
"author_profile": "https://Stackoverflow.com/users/474708",
"pm_score": 4,
"selected": false,
"text": "AccessControl::GrantOnFile \"<folder>\" \"(BU)\" \"FullAccess\" AccessControl::GrantOnFile \"<folder>\" \"(S-1-5-32-545)\" \"FullAccess\""
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074/"
] |
116,888
|
<p>Given this data:</p>
<pre><code>CREATE TABLE tmpTable(
fldField varchar(10) null);
INSERT INTO tmpTable
SELECT 'XXX'
UNION ALL
SELECT 'XXX'
UNION ALL
SELECT 'ZZZ'
UNION ALL
SELECT 'ZZZ'
UNION ALL
SELECT 'YYY'
SELECT
CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField
FROM tmpTable
</code></pre>
<p>The expected resultset is:<br>
XXX<br>
XXX<br>
XXX<br>
XXX<br>
OTH </p>
<p>What situation would casue SQL server 2000 to NOT find 'YYY'? And return the following as the resultset:<br>
XXX<br>
XXX<br>
XXX<br>
XXX<br>
XXX </p>
<p>The problem is with the like 'YYY', I have found other ways to write this to get it to work, but I want to know why this exact method doesn't work. Another difficulty is that it works in most of my SQL Server 2000 environments. I need to find out what is different between them to cause this. Thanks for your help.</p>
|
[
{
"answer_id": 116924,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": -1,
"selected": false,
"text": "SELECT CASE fldField WHEN 'YYY' \nTHEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable\n"
},
{
"answer_id": 116932,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 0,
"selected": false,
"text": "fldField = '%YYY%'"
},
{
"answer_id": 117265,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CASE WHEN fldField like '%YYY%' THEN \n 'OTH' \n ELSE 'XXX'\n END AS newField \nFROM\n tmpTable\n SELECT\n CASE WHEN fldField = 'YYY' THEN \n 'OTH' \n ELSE 'XXX'\n END AS newField \nFROM\n tmpTable\n"
},
{
"answer_id": 117397,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 0,
"selected": false,
"text": "Declare @tmpTable TABLE(\nfldField varchar(10) null);\n\nINSERT INTO @tmpTable\nSELECT 'XXX'\nUNION ALL \nSELECT 'XXX'\nUNION ALL\nSELECT 'ZZZ'\nUNION ALL\nSELECT 'ZZZ'\nUNION ALL\nSELECT 'YYY'\nUNION ALL\nSELECT 'YYY' + Char(10)\n\nSELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS YourOriginalTest,\n CASE WHEN fldField like 'YYY%' THEN 'OTH' ELSE 'XXX' END AS newField\nFROM @tmpTable\n Select *\nFrom Table\nWhere Column Like '%[' + Char(10) + Char(9) + Char(13) + ']%'\n"
},
{
"answer_id": 117468,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE dbo.TestLike ( my_field varchar(10) null);\nGO\nCREATE CLUSTERED INDEX IDX_TestLike ON dbo.TestLike (my_field)\nGO\nINSERT INTO dbo.TestLike (my_field) VALUES ('XXX')\nINSERT INTO dbo.TestLike (my_field) VALUES ('XXX')\nINSERT INTO dbo.TestLike (my_field) VALUES ('ZZZ')\nINSERT INTO dbo.TestLike (my_field) VALUES ('ZZZ')\nINSERT INTO dbo.TestLike (my_field) VALUES ('YYY')\nGO\n\nSELECT\n my_field,\n case my_field when 'YYY' THEN 'Y' ELSE 'N' END AS C2,\n case when my_field like 'YYY' THEN 'Y' ELSE 'N' END AS C3,\n my_field\nFROM dbo.TestLike\nGO\n my_field C2 C3 my_field\n---------- ---- ---- ----------\nN XXX N XXX\nN XXX N XXX\nY YYY N YYY\nN ZZZ N ZZZ\nN ZZZ N ZZZ\n"
},
{
"answer_id": 118231,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 0,
"selected": false,
"text": "SELECT\n CASE\n WHEN fldField like 'YYY ' -- 7 spaces\n THEN 'OTH'\n ELSE 'XXX'\n END as newField\nfrom tmpTable\n"
},
{
"answer_id": 121432,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 2,
"selected": true,
"text": "SELECT @@version"
},
{
"answer_id": 9697393,
"author": "Avinash",
"author_id": 1268320,
"author_profile": "https://Stackoverflow.com/users/1268320",
"pm_score": 0,
"selected": false,
"text": "SELECT\nCASE \n WHEN fldField like '%YYY%' THEN 'OTH' \n ELSE 'XXX' END AS newField\nEND\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12470/"
] |
116,894
|
<p>I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've worked with. So, even though my application is working, I'm curious whether there is a better way to accomplish my goals.</p>
<p>Specifics: How does one typically implement the request-transform-render database workflow in Python? Currently, I am using pyodbc to fetch data, copying the results into attributes on an object, performing some calculations and merges using a list of these objects, then rendering the output from the list of objects. (Sample code below, SQL queries redacted.) Is this sane? Is there a better way? Are there any specific "gotchas" I've stumbled into in my relative ignorance of Python? I'm particularly concerned about how I've implemented the list of rows using the empty "Record" class.</p>
<pre><code>class Record(object):
pass
def calculate_pnl(records, node_prices):
for record in records:
try:
# fill RT and DA prices from the hash retrieved above
if hasattr(record, 'sink') and record.sink:
record.da = node_prices[record.sink][0] - node_prices[record.id][0]
record.rt = node_prices[record.sink][1] - node_prices[record.id][1]
else:
record.da = node_prices[record.id][0]
record.rt = node_prices[record.id][1]
# calculate dependent values: RT-DA and PNL
record.rtda = record.rt - record.da
record.pnl = record.rtda * record.mw
except:
print sys.exc_info()
def map_rows(cursor, mappings, callback=None):
records = []
for row in cursor:
record = Record()
for field, attr in mappings.iteritems():
setattr(record, attr, getattr(row, field, None))
if not callback or callback(record):
records.append(record)
return records
def get_positions(cursor):
# get the latest position time
cursor.execute("SELECT latest data time")
time = cursor.fetchone().time
hour = eelib.util.get_hour_ending(time)
# fetch the current positions
cursor.execute("SELECT stuff FROM atable", (hour))
# read the rows
nodes = {}
def record_callback(record):
if abs(record.mw) > 0:
if record.id: nodes[record.id] = None
return True
else:
return False
records = util.map_rows(cursor, {
'id': 'id',
'name': 'name',
'mw': 'mw'
}, record_callback)
# query prices
for node_id in nodes:
# RT price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, time, time)).fetchone()
rt5 = row.lmp if row else None
# DA price
row = cursor.execute("SELECT price WHERE ? ? ?", (node_id, hour, hour)).fetchone()
da = row.da_lmp if row else None
# update the hash value
nodes[node_id] = (da, rt5)
# calculate the position pricing
calculate_pnl(records, nodes)
# sort
records.sort(key=lambda r: r.name)
# return the records
return records
</code></pre>
|
[
{
"answer_id": 117769,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": ">>> a={'col1': 'foo', 'col2': 'bar', 'col3': 'wibble'}\n>>> 'Col1=%(col1)s, Col2=%(col2)s, Col3=%(col3)s' % a\n'Col1=foo, Col2=bar, Col3=wibble'\n>>> \n"
},
{
"answer_id": 117994,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": true,
"text": "class Record( object ):\n \"\"\"Assuming rtda and pnl must exist.\"\"\"\n def __init__( self ):\n self.da= 0\n self.rt= 0\n self.rtda= 0 # or whatever\n self.pnl= None # \n self.sink = None # Not clear what this is\n def setPnl( self, node_prices ):\n # fill RT and DA prices from the hash retrieved above\n # calculate dependent values: RT-DA and PNL\n calculate_pnl( records, node_prices ) def calculate_pnl( records, node_prices ):\n for record in records:\n record.setPnl( node_prices )\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19031/"
] |
116,896
|
<p>I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).</p>
<p>e.g. I want the debugger to break at the exception:</p>
<pre><code>try
{
System.IO.File.Delete(someFilename);
}
catch (Exception)
{
//we really don't care at runtime if the file couldn't be deleted
}
</code></pre>
<p>I came across <a href="http://www.syncfusion.com/faq/windowsforms/faq_c60c.aspx#q583q" rel="noreferrer">these</a> notes for Visual Studio.NET:</p>
<blockquote>
<p>1) In VS.NET go to the Debug Menu >>
"Exceptions..." >> "Common Language
Runtime Exceptions" >> "System" and
select "System.NullReferenceException"</p>
<p>2) In the bottom of that dialog there
is a "When the exception is thrown:"
group box, select "Break into the
debugger" </p>
<p>3) Run your scenario. When the
exception is thrown, the debugger will
stop and notify you with a dialog that
says something like:
"An exception of type "System.NullReferenceException" has
been thrown.
[Break] [Continue]" </p>
<p>Hit [Break]. This will put you on the
line of code that's causing the
problem.</p>
</blockquote>
<p>But they do not apply to Visual Studio 2005 (there is no <strong>Exceptions</strong> option on the <strong>Debug</strong> menu).</p>
<p>Does anyone know where the find this options dialog in Visual Studio that the "<em>When the exception is thrown</em>" group box, with the option to "<em>Break into the debugger</em>"?</p>
<p><em>Update: The problem was that my <strong>Debug</strong> menu didn't have an <strong>Exceptions</strong> item. I customized the menu to manually add it.</em></p>
|
[
{
"answer_id": 434023,
"author": "Spencer Ruport",
"author_id": 52551,
"author_profile": "https://Stackoverflow.com/users/52551",
"pm_score": 2,
"selected": false,
"text": "if(!GlobalTestingBool)\n{\n try\n {\n SomeErrorProneMethod();\n }\n catch (...)\n {\n // ... Error handling ...\n }\n}\nelse\n{\n SomeErrorProneMethod();\n}\n"
},
{
"answer_id": 47681894,
"author": "Sameer Alibhai",
"author_id": 2343,
"author_profile": "https://Stackoverflow.com/users/2343",
"pm_score": 5,
"selected": false,
"text": "ArgumentNullException"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
116,905
|
<p>I would like to use my laptop as a web development (PHP, Python, etc.) machine, but I'm hesitant to do this unless I can ensure that it can not be accessed by the outside world.</p>
<p>I'm guessing that something more than a firewall is necessary, such as configurations to the Apache configuration files, but I'm not sure what else I would need to be 100% sure it's locked down tightly.</p>
|
[
{
"answer_id": 116920,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": true,
"text": "Listen 127.0.0.1\n <Directory \"/var/www/localhost/htdocs\">\nAllowOverride None\nDeny from all\nAllow from 127.0.0.1/255.0.0.0\n</Directory>\n"
},
{
"answer_id": 116923,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "127.0.0.1:80"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
116,951
|
<p>I wanted to use <code>fstream</code> to read a txt file.</p>
<p>I am using <code>inFile >> characterToConvert</code>, but the problem is that this omits any spaces and newline.</p>
<p>I am writing an encryption program so I need to include the spaces and newlines.</p>
<p>What would be the proper way to go about accomplishing this?</p>
|
[
{
"answer_id": 116980,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "\n#include <iostream>\n#include <fstream>\n#include <string>\nusing namespace std;\n\nint main () \n{\n string line;\n ifstream myfile (\"foo.txt\");\n\n if (myfile.is_open()){\n\n while (!myfile.eof()){\n getline (myfile,line);\n cout << line << endl;\n }\n myfile.close();\n }\n return 0;\n}\n"
},
{
"answer_id": 117015,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 5,
"selected": false,
"text": "std::ifstream ifs(\"foobar.txt\", std::ios::binary);\n\nifs.seekg(0, std::ios::end);\nstd::ifstream::pos_type filesize = ifs.tellg();\nifs.seekg(0, std::ios::beg);\n\nstd::vector<char> bytes(filesize);\n\nifs.read(&bytes[0], filesize);\n"
},
{
"answer_id": 117018,
"author": "Adam Holmberg",
"author_id": 20688,
"author_profile": "https://Stackoverflow.com/users/20688",
"pm_score": 4,
"selected": false,
"text": "inFile.unsetf(ios_base::skipws);\n"
},
{
"answer_id": 117146,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 2,
"selected": false,
"text": "int fstream::get() istream& fstream::read(char*, streamsize) get() ios::binary read()"
},
{
"answer_id": 117228,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 6,
"selected": false,
"text": "rdbuf() std::ifstream in(\"myfile\");\n\nstd::stringstream buffer;\nbuffer << in.rdbuf();\n\nstd::string contents(buffer.str());\n"
},
{
"answer_id": 117763,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 2,
"selected": false,
"text": "std::filebuf myfile;\nmyfile.open( \"myfile.dat\", std::ios_base::in | std::ios_base::binary );\n\n// gets next char, then moves 'get' pointer to next char in the file\nint ch = myfile.sbumpc();\n\n// get (up to) the next n chars from the stream\nstd::streamsize getcount = myfile.sgetn( char_array, n );\n"
},
{
"answer_id": 119331,
"author": "Flame",
"author_id": 5387,
"author_profile": "https://Stackoverflow.com/users/5387",
"pm_score": 0,
"selected": false,
"text": "#include <fstream>\n#include <iomanip>\n\n\nifstream ifs (\"file\");\nifs >> noskipws\n"
},
{
"answer_id": 5646370,
"author": "Iakov Minochkin",
"author_id": 501213,
"author_profile": "https://Stackoverflow.com/users/501213",
"pm_score": 2,
"selected": false,
"text": "std::ifstream ifs( \"filename.txt\" );\n\nstd::string str( ( std::istreambuf_iterator<char>( ifs ) ), \n std::istreambuf_iterator<char>()\n );\n"
},
{
"answer_id": 11590855,
"author": "MCA",
"author_id": 710576,
"author_profile": "https://Stackoverflow.com/users/710576",
"pm_score": 0,
"selected": false,
"text": "ifstream ifile(path);\nstd::string contents((std::istreambuf_iterator<char>(ifile)), std::istreambuf_iterator<char>());\nifile.close();\n"
},
{
"answer_id": 12102853,
"author": "user1621518",
"author_id": 1621518,
"author_profile": "https://Stackoverflow.com/users/1621518",
"pm_score": 2,
"selected": false,
"text": "ifstream inputFile(\"test.data\");\n\nstring fileData(istreambuf_iterator<char>(inputFile), istreambuf_iterator<char>());\n"
},
{
"answer_id": 44571611,
"author": "jdhao",
"author_id": 6064933,
"author_profile": "https://Stackoverflow.com/users/6064933",
"pm_score": 0,
"selected": false,
"text": "std::ios_base::skipws #include <iostream>\n#include <fstream>\n#include <string>\n\nint main(){\n std::ifstream in_file(\"input.txt\");\n\n char s;\n\n if (in_file.is_open()){\n int count = 0;\n while (in_file.get(s)){\n\n std::cout << count << \": \"<< (int)s <<'\\n';\n count++;\n }\n\n }\n else{\n std::cout << \"Unable to open input.txt.\\n\";\n }\n in_file.close();\n\n return 0;\n }\n cat input.txt ab cd\nef gh\n 0: 97\n1: 98\n2: 32\n3: 99\n4: 100\n5: 10\n6: 101\n7: 102\n8: 32\n9: 103\n10: 104\n11: 32\n12: 10\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
116,957
|
<p>What java GUI layout manager does everyone use? Lately, I have been using <a href="http://www.miglayout.com/" rel="nofollow noreferrer">MigLayout</a>, which has some powerful component controls. Just wanted to see what other developers are using other than the standard JDK ones.</p>
|
[
{
"answer_id": 122063,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 2,
"selected": false,
"text": "GridBagLayout BorderLayout FlowLayout BoxLayout GridBagLayout"
},
{
"answer_id": 333165,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": " private void layoutComponents(){\n JPanel panel = new JPanel();\n\n GroupLayout layout = new GroupLayout(panel);\n panel.setLayout(layout);\n\n layout.setAutoCreateGaps(true);\n\n layout.setAutoCreateContainerGaps(true);\n SequentialGroup hGroup = layout.createSequentialGroup();\n\n JLabel nameLbl = new JLabel(\"Name\");\n JLabel countLbl = new JLabel(\"Amount\");\n JLabel dateLbl = new JLabel(\"Date(dd/MM/yy)\");\n hGroup.addGroup(layout.createParallelGroup().\n addComponent(nameLbl).\n addComponent(countLbl).\n addComponent(dateLbl).\n addComponent(go));\n\n hGroup.addGroup(layout.createParallelGroup().\n addComponent(name).\n addComponent(count).\n addComponent(date));\n\n layout.setHorizontalGroup(hGroup);\n\n SequentialGroup vGroup = layout.createSequentialGroup();\n\n vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).\n addComponent(nameLbl).addComponent(name));\n vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).\n addComponent(countLbl).addComponent(count));\n vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).\n addComponent(dateLbl).addComponent(date));\n vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).\n addComponent(go));\n layout.setVerticalGroup(vGroup);\n\n frame.add( panel , BorderLayout.NORTH );\n frame.add( new JScrollPane( textArea ) );\n }\n"
},
{
"answer_id": 415586,
"author": "jfpoilpret",
"author_id": 1440720,
"author_profile": "https://Stackoverflow.com/users/1440720",
"pm_score": 3,
"selected": false,
"text": "DesignGridLayout DesignGridLayout DesignGridLayouut layout = new DesignGridLayout(myPanel);\nlayout.row().grid(lblFirstName).add(txfFirstName).grid(lblSurName).add(txfSurName);\nlayout.row().grid(lblAddress).add(txfAddress);\nlayout.row().center().add(btnOK, btnCancel);\n DesignGridLayout"
},
{
"answer_id": 1663306,
"author": "devx",
"author_id": 201182,
"author_profile": "https://Stackoverflow.com/users/201182",
"pm_score": 2,
"selected": false,
"text": " PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);\n\n gbl.row().cell(lblFirstName).cell(txtFirstName).fillX()\n .cell(lblFamilyName).cell(txtFamilyName).fillX();\n gbl.row().cell(lblAddress).cellXRemainder(txtAddress).fillX();\n\n gbl.doneAndPushEverythingToTop();\n"
},
{
"answer_id": 20108491,
"author": "hageldave",
"author_id": 1927471,
"author_profile": "https://Stackoverflow.com/users/1927471",
"pm_score": 0,
"selected": false,
"text": "parent.add(child,\"topleft(0, 0.5)bottomright(0.5,1.0)\");"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6186/"
] |
116,967
|
<p>Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?</p>
<p>Like this:</p>
<pre><code><IMG SRC="GetImage()" />
<script language="javascript">
function GetImage() {return "imageName/imagePath.jpg"}
</script>
</code></pre>
<p>This is using .NET 2.0.</p>
|
[
{
"answer_id": 116981,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 1,
"selected": false,
"text": "<img src=\"\" id=\"myImage\"/>\n<script type=\"text/javascript\">\n document.getElementById(\"myImage\").src = GetImage();\n</script>\n"
},
{
"answer_id": 116990,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 5,
"selected": true,
"text": "<img src=\"blank.png\" id=\"image\" alt=\"just nothing\">\n<script type=\"text/javascript\">\n document.getElementById('image').src = \"yourpicture.png\";\n</script>\n"
},
{
"answer_id": 116991,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": 0,
"selected": false,
"text": "<img src='images/test.jpg' onmouseover=\"alert(this.src);\"> \n"
},
{
"answer_id": 116995,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": 0,
"selected": false,
"text": "runat=\"server\" src"
},
{
"answer_id": 117418,
"author": "ceetheman",
"author_id": 16154,
"author_profile": "https://Stackoverflow.com/users/16154",
"pm_score": 1,
"selected": false,
"text": "<img src=\"provideImage.aspx?someparameter=x\" />\n"
},
{
"answer_id": 118366,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": false,
"text": "<img src=\"javascript:GetImage()\" />\n function getImageUrl(img) {\n var imageSrc = \"imageName/imagePath.jpg\";\n if(img.src != imageSrc) { // don't get stuck in an endless loop\n img.src = imageSrc;\n }\n}\n <img src=\"http://yourdomain.com/images/empty.gif\" onload=\"getImageUrl(this)\" />\n"
},
{
"answer_id": 4027479,
"author": "jdizzle",
"author_id": 70603,
"author_profile": "https://Stackoverflow.com/users/70603",
"pm_score": 4,
"selected": false,
"text": "<img src='blah' onerror=\"this.src='url to image'\">\n"
},
{
"answer_id": 10512781,
"author": "dodysugianto",
"author_id": 1384114,
"author_profile": "https://Stackoverflow.com/users/1384114",
"pm_score": 0,
"selected": false,
"text": "var imgsBlocks = new Array( '/1.png', '/2.png', '/3.png');\nfunction getImageUrl(elemid) { \nvar ind = document.getElementById(elemid).selectedIndex;\ndocument.getElementById(\"get_img\").src=imgsBlocks[ind]; \n}\n <img src=\"'+imgsBlocks[2]+'\" id=\"get_img\"/>\n"
},
{
"answer_id": 74036810,
"author": "saisuresh",
"author_id": 11801147,
"author_profile": "https://Stackoverflow.com/users/11801147",
"pm_score": 0,
"selected": false,
"text": "const myImage = new Image(200, 200);\nmyImage.src = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBEPEQ8PDxEPEQ8PEQ8PDw8RDxEPDw8PGBQZGRkUGBgcIS4lHB4rHxgYJzsmKzMxNzc1GiRIRTszPzA0QzEBDAwMEA8QGRISHjEhISE2MTQ0NDQxMTE0MTExMTQ0NDQ0NDExMTE0NDE0MTExMTQ0NDQ0MTQxMTExPzExNDQxMf/AABEIAM4A9QMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAAAQcCBQYEA//EAEgQAAIBAgIDCwgIBAMJAAAAAAABAgMEERIFBiEHExYxNFR0krKz0jIzNVFhcnOTIkFCYnGRodEVgZTBI1LwFBckJVOio7HC/8QAGQEBAAMBAQAAAAAAAAAAAAAAAAEDBAUC/8QAKxEBAAIABAUDAwUBAAAAAAAAAAECAxExUQQTFDKBEiEzQXGxImGh0fAj/9oADAMBAAIRAxEAPwC5gAAAAAgwqVFFOUmlFJtybwSS42yvNOa+1HKULKMVCLw36azOXtjHiS9rx/ke8PDtiTlV4veK6rGBTj1v0jziXy6fhIet2kecy6lPwmjo8TeFfPquQFNcLtI85n1KfhIet+kecy6lPwkdHibwnn1XMCmeF+kecz6lLwmPDDSPOZ9Wn4R0eJvBz6roBS/DDSPOZ9Sn4SOGGkecz6lPwjpL7x/vBz6rpBSz1w0jzmfVp+EjhhpLnMurT8I6S+8HPquoFK8MdJc5n1KXhJ4YaR51PqU/COkv+xz67SukFLcMNI85n1KfhHDDSPOZ9Sn4R0l/2OfXaV0gpbhhpHnU+pT8I4X6R5zLq0/CR0l94OfVdIKX4X6S5zPqU/CFrfpHnM+pT8I6S/7HPrtK6CSmaWuekIvNv+f7s4U3F/jgkdxqrrjC9kqFaKpXGH0UsclXDjy48T9j/U8X4e9Izeq4tbTk64AFKwAAAAAAAAAAHH7o99KnaxpReDuJ5Ze2EVma/m8EVeiw91LyLP363ZiV6dXhIyw48seNP60MgkM0qWGBDMmYshIQySGBBBLIIkQyDIggAMQglBJAxIGSRkomOJKkBLIJxIJEmVGrKnOE4PLOEozjJbGpJ4pmJDIF96Nut/oUK3FvtOnUw9WaKeH6nrNTqtyCx6NQ7CNscafaZhvjQABCQAAAAAAAHBbqXkWfv1ezErwsPdS8iz9+r2YldnW4T4o8/lixu+QMhkmhUgxZkyGBABBCUMgkggCMQCAxIxIbLD1Q1IjKMbm+jmzJTp27xSS405+v3fzK8TErhxnL3Wk20cZo3Q9zdvChQqTX1zy5aa/Gb2fyxOltdzm7mk6tahS9iUqsl+WC/UtGnTjCKjFKMUsFGKSSXsSMzDbirzp7NEYNfqr+nuZw+3dzb+5RhD/22fX/AHa2/Objq0/2O7JK+fibvXKpsq7WPUinZWtW5jXqTdPJhCUYJPNUjHjXvHEplxboPo25/Gh30CnEbeGva9Zm3v7s+LWKzlDMxZkYs0K15ar8gsejUOwjamq1X5BY9Ft+wjanGtrLfGkAAISAAAAAAAA4LdT83Z/Eq9lFdFi7qfm7P36vZRXZ1+E+KPP5YsbvlDBANGapDDJMWEoIMzFkCCCSCBAYDZA6bULQivLnPUWNG2yVJp8UqmP0I+3am2vZ7S4kczqBYKhYUZYYSr415P62peT/ANuB0xyce/rvO0NuHXKqQCClYkHNaS11sLaThKpKrUWyUaMd8wfqctkf1NTLdLtvs29y1626Uf8A6LIwcSfeIeJxKx9W23QvRtz+NDvoFNxO61k12oX1pVtoUq8KlR03FzUMiyzjJ4tSx4ov6jhkb+GpatJi0Ze7Pi2ibewGTiQ2aFS89WOQWPRbfsI2pq9WeQ2PRbfu4m0OLbWW+ukAAISAAAAAAAA4HdT83Z/Eq9hFeFibqfm7P4lXsIrs6/CfFHn8sWN3yxIZkQaFSCGZEMhIQSYgRgRgZmBACEM8owXHOUYL8W8P7ks9Wh4Z7q1i/tXFBf8AkiebTlGaYXtbUVTp04LYoQjFL1JJL+x9wDiOgHA7penJ0YQs6UnCVaLlWktj3riUU/qxeOPsXtO+Kf3SZ5tIyX+ShRj+eaX9y/h6xbEjNXizlVyijgsFgl6icCQdRjMCUQSgAYDAvTVnkNj0W37uJtDV6tchsei2/YibQ4ttZb66QAAhIAAAAAAADgd1Pzdn8Sr2EV2WLup+bs/iVewiuzrcJ8UeWLG75DFmRjgaZVBDJIZCQhkkEAYtmR2W5paUq1W5VanTqKNOm4qpCM1F5ntWZbCvFv6KzbZ6rX1Tk4py/wBYnv1ff/GWfSbftouj+C2nNLX+npfsTDQ1rFxlC2toyi1KMo0KcZRkuJppbGY54yJjL0/yujAndsAAYmkKZ3Q3/wAyr+yFDsIuY8NfRdtVk51LehObwTnOjCcmlxYtrEtwcTl2zyzeL19UZKDxGJfP8Ds+aWv9PS/YfwSz5pa/09L9jT1kbKeRO6hsTJFra9aMtqWj7idO3t4Ti6OE4UYQksasE8GlitjZVKNOFicyueiu9PTOQSyCWWPC89WuQ2PRbfu4m0NXq1yGx6Lb92jaHFnWW+NIAAQkAAAAAAABwO6n5uz+JV7CK8LE3U/N2fv1eyiuzr8J8UefyxY3fIQSyGaVSCGAyEhDJBAxZ3W5T567+HT7cjhjudyrz138Kn25Gfifit/vqswu+FmAgHJbUgAAAQBIIAHNboXoy596h30CnUXFuh+jbj3rfvoFOnR4P45+7Lj9zIhkkM1KV56tchsei2/do2hq9WuQ2PRbfu0bQ4s6y310gABCQAAAAAAAHA7qXm7T36vZRXhYe6n5u09+r2UV4dfhPijz+WLG75CCSDRKpAZJDISgAMCD16M0tcWcpStqjpymlGTUKc8yTxS+kn6zyMhnmYiYylMezfcNNJc6l8mh4D16H1t0hUuranO4coVK9KE471RWaMppNYqGK2HKnu0Byyz6TQ7cSm+FT0z7R9fo9Re2ce6+QAcluCsNcdZr62vq1ChXcKUY0nGO90pYOUE3tlFvjLPKZ3QPSVx7tDu4mjhqxa+U+/sqxpmK+zDhnpLnT+TQ8A4Z6S5zL5NDwGgB0OVTaGb1W3be/wBZb25pyo167nTnlcob3SjjlkpLbGKfGkalAHqtYr7Q8zMzqkhmRiyRemrfIrLo1v3cTZms1c5FZdGt+7ibM4s6y3xpAACEgAAAAAAAOC3U/N2fv1eyivCw91Lzdn8Sr2EV2dfhPijz+WLG75CCTE0KkkMkghIQwQwIYDMSBke3QHLLPpNv24nhPdoDlln0m37cTxftn7S9RrC+QAcVvCmt0D0lX92h3cS5Smd0D0lce7Q7uJp4T5PCnH7XOgkg6TKkAASQySGBeurnIrLotv3cTZGt1c5FZdFt+7ibI4s6y310gABCQAAAAAAAHB7qXm7T4lTsortFibqXm7T4lTsoro6/CfFHn8sWN3ykxJBpVIIZJDISEAhkCTEMxIA9+gOWWfSaHbieA9+gOWWfSaHbieL9s/aXqNYXyADit4Uzug+krj3aHdxLmKZ3QfSVz7tDuomnhPk8Kcftc8AQdJkSAAMjFmZgwleurvIrLotv3cTZGs1d5FZdFt+7ibM4s6y310gABCQAAAAAAAHB7qXm7T4lTsIrss7dKs5VLWFWKx3iopT9kJLK3+eUrDE63Bz/AMo8sWNH60kEkM1KkGLMiGQlBizIxZAkwMzAgD36A5ZZ9Jt+3E8LPdoDlln0m37cTxftn7S9RrC+QAcVvCmd0H0lc+7Q7qJcxTO6D6Sufdod1E08J8nj+lOP2ueIAOkypAAQyMWQZ06cpyjCCcpzkoQS+uTeCX5hK8tXeRWXRbfu4mzPLo633mjRo/8ASp06f45Ypf2PUcWdXQjQABAAAADCE1JKUWnFpNNPFNPiaZmAAAHxrUozjKE0pQmnGUWsVKLWDTK105qJXpylOzwq0Xi1TcsKsPu7dkl7ccfxLQILMPFthznV4vSLaqRer96nh/slxs+42Rwfvea3Hy2XfgDT1t9oV9PXdR/B+95pcfLYer99zS4+Wy8BgOtvtH8/2ciN5UfwevuaXHy2Y8Hr7mlx1GXlgMCOtvtByI3lRnB2+5pc/LY4O33NLjqMvMkdZfaP5ORG6i+Dt9zS46jPZoXQN7C6tZzta8YQuKMpycGlGKmm2y5xgeZ4u0xllBGBWPqkAGVeFT67aGuq1/XqUretUhKNFRnCDcXhTing/wAUWwRgWYeJOHOcPN6+qMlF8Hb7mlx1GODt9zW4+Wy9MBgX9ZbaFXIjdRnB6+5pcfLY4O33NLn5bLzGA6u20HIjdSNDVi/m1GNpWXtnFQiv5yZ3WqOpqtJK4uXGdwvIjHFwo4ra8X5UtvH9R2oPF+IveMtHquFWs5oRIBnWgAAAADXav8js+i2/dxNia7V/kdn0W37uJsQAAAAAAAAPLeXkKEYyqNpSlGEcsJzk5y4koxTZ4rTTVOpJwnjCpvtSko5ZuMstScE1LLg/J24cTeDPbe2kLinKnUzZJbJKMnHMuLB4fUeaehqLy7Jpwc5QlGpNSi51d8bTx/zfpsA8tPWSjOUYxjWcZ1Y0Yz3mooPNQ35Sxy7Fl/fiM6WslpUjmhWzxSm2406klGMYxlKTwjsWWcXi9m0+tLQdvFRUYzSjKnJLfJtKUaW9J8f1weV+tH0o6LpU1HB1PowlTg3VnKUaclBNJt7PIj+QHyenKKqSg1VWFOhVUt4q/T3yU4xillxcsY8X7M+dzrBQjFVIzUoKdGFSbU4U4Kc4xeMmsFJKSeV7fwPotC0FhgpppQimqk01knKpF8fGnKW37zXEI6Bt1FwyyyYwnKm5ycJTi01NpvbJ5Vi3xgemrf04qnmzp1VjBb3NywwTbcUsYpYrFvDA8stYLVLM5ywwzeZreRlzZ/J8nBN5uLZxn3ejabVNN1G6Kyxlvk82VxScXLHFppLHHjaPjHQdulJZZtOnKjtqTbVJxcci27Ek3h6sWB6aOkKU4xmppKdSVKKlF05OpFyTjlkk1LGMtj9R4rvTcaU60JRj/hOEVmqZZScsn0sGsFBZ1jLHZg9hs7e3jSUlFYKU51Htb+nOTk3+bZ8Kuj6cpynJ1HKUJwX+JPCEZJKWVY/RbwW1AeCGnc6ouNGco11UUMtSDc5wU24x+px+j5WK8qP1Y4IafTbUqUkqc4wryzxcaeaq6cXF/aWZPF7MMGeuroejPDzkUoqMIwqzhGGEXBSST2SUW1ij5LQdvhFSUpQglDJKTcJwi8YwlHilFPFpP1sD4z0+lGdSNGbhTqqm5OUY4xcacoyS+8qiwTw4ni0Zz0xLJXnGEGrdzzRlWlCpki5LM45HxuOxbcTPg/arOoUlTjUljUhSbpQqfRjHLKMcE44QWz8fWz7vRlPFylnlKUqbbnOU/Jk5Rjt+ypPHAD1UZSlGLlHLJxi5RxTcZNbY4rjwPsAAAAAAAAAAAAH/2Q==';\ndocument.body.appendChild(myImage);"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20682/"
] |
116,968
|
<p>I have a database full of customer data. It's so big that it's really cumbersome to operate on, and I'd rather just slim it down to 10% of the customers, which is plenty for development. I have an awful lot of tables and I don't want to alter them all with "ON DELETE CASCADE", especially because this is a one-time deal.</p>
<p>Can I do a delete operation that cascades through all my tables without setting them up first? If not, what is my best option?</p>
|
[
{
"answer_id": 117239,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 3,
"selected": false,
"text": "Tbl_A_MyFK ALTER TABLE Tbl_A DROP CONSTRAINT Tbl_A_MyFK Tbl_A_MyFK ALTER TABLE Tbl_A ADD CONSTRAINT Tbl_A_MyFK FOREIGN KEY (MyFK) REFERENCES Tbl_B(Column) ON DELETE CASCADE DELETE FROM Tbl_A WHERE ... Tbl_A_MyFK ALTER TABLE Tbl_A DROP CONSTRAINT Tbl_A_MyFK Tbl_A_MyFK ALTER TABLE Tbl_A ADD CONSTRAINT Tbl_A_MyFK FOREIGN KEY (MyFK) REFERENCES (Tbl_B)"
},
{
"answer_id": 118167,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 7,
"selected": true,
"text": "ON DELETE CASCADE GO create procedure usp_delete_cascade (\n @base_table_name varchar(200), @base_criteria nvarchar(1000)\n)\nas begin\n -- Adapted from http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7\n -- Expects the name of a table, and a conditional for selecting rows\n -- within that table that you want deleted.\n -- Produces SQL that, when run, deletes all table rows referencing the ones\n -- you initially selected, cascading into any number of tables,\n -- without the need for \"ON DELETE CASCADE\".\n -- Does not appear to work with self-referencing tables, but it will\n -- delete everything beneath them.\n -- To make it easy on the server, put a \"GO\" statement between each line.\n\n declare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_name varchar(200) not null,\n processed bit not null,\n delete_sql varchar(1000)\n )\n\n insert into @to_delete (criteria, table_name, processed) values (@base_criteria, @base_table_name, 0)\n\n declare @id int, @criteria nvarchar(1000), @table_name varchar(200)\n while exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc\n\n insert into @to_delete (criteria, table_name, processed)\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')',\n referencing_table.name,\n 0\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n update @to_delete set\n processed = 1\n where id = @id\n end\n\n select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc\nend\n\nexec usp_delete_cascade 'root_table_name', 'id = 123'\n"
},
{
"answer_id": 5505602,
"author": "dan",
"author_id": 686446,
"author_profile": "https://Stackoverflow.com/users/686446",
"pm_score": 1,
"selected": false,
"text": "declare @deleteSql nvarchar(1200)\ndeclare delete_cursor cursor for\nselect table_name, criteria \nfrom @to_delete\norder by id desc\n\nopen delete_cursor\n\nfetch next from delete_cursor\ninto @table_name, @criteria\n\nwhile @@fetch_status = 0\nbegin\n select @deleteSql = 'delete from ' + @table_name + ' where ' + @criteria\n --print @deleteSql\n-- exec sp_execute @deleteSql\nEXEC SP_EXECUTESQL @deleteSql\n\n fetch next from delete_cursor\n into @table_name, @criteria\nend\nclose delete_cursor\ndeallocate delete_cursor\n"
},
{
"answer_id": 7691473,
"author": "kevin_fitz",
"author_id": 251056,
"author_profile": "https://Stackoverflow.com/users/251056",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE usp_delete_cascade (\n @base_table_schema varchar(100), @base_table_name varchar(200), @base_criteria nvarchar(1000)\n)\nas begin\n\n -- Expects the name of a table, and a conditional for selecting rows\n -- within that table that you want deleted.\n -- Produces SQL that, when run, deletes all table rows referencing the ones\n -- you initially selected, cascading into any number of tables,\n -- without the need for \"ON DELETE CASCADE\".\n -- Does not appear to work with self-referencing tables, but it will\n -- delete everything beneath them.\n -- To make it easy on the server, put a \"GO\" statement between each line.\n\n declare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_schema varchar(100),\n table_name varchar(200) not null,\n processed bit not null,\n delete_sql varchar(1000)\n )\n\n insert into @to_delete (criteria, table_schema, table_name, processed) values (@base_criteria, @base_table_schema, @base_table_name, 0)\n\n declare @id int, @criteria nvarchar(1000), @table_name varchar(200), @table_schema varchar(100)\n while exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name, @table_schema = table_schema from @to_delete where processed = 0 order by id desc\n\n insert into @to_delete (criteria, table_schema, table_name, processed)\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_schema + '].[' + @table_name +'] where ' + @criteria + ')',\n schematable.name,\n referencing_table.name,\n 0\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.schemas schematable on referencing_table.schema_id = schematable.schema_id\n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n update @to_delete set\n processed = 1\n where id = @id\n end\n\n select 'print ''deleting from ' + table_name + '...''; delete from [' + table_schema + '].[' + table_name + '] where ' + criteria from @to_delete order by id desc\nend\n\nexec usp_delete_cascade 'schema', 'RootTable', 'Id = 123'\nexec usp_delete_cascade 'schema', 'RootTable', 'GuidId = ''A7202F84-FA57-4355-B499-1F8718E29058'''\n"
},
{
"answer_id": 8214267,
"author": "croisharp",
"author_id": 745682,
"author_profile": "https://Stackoverflow.com/users/745682",
"pm_score": 2,
"selected": false,
"text": "DECLARE @commandText VARCHAR(8000)\n DECLARE curDeletes CURSOR FOR\n select 'delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc\n\n OPEN curDeletes\n FETCH NEXT FROM curDeletes\n INTO\n @commandText\n\n WHILE(@@FETCH_STATUS=0)\n BEGIN\n EXEC (@commandText)\n FETCH NEXT FROM curDeletes INTO @commandText\n END\n CLOSE curDeletes\n DEALLOCATE curDeletes\n"
},
{
"answer_id": 12833632,
"author": "Neil",
"author_id": 1547203,
"author_profile": "https://Stackoverflow.com/users/1547203",
"pm_score": 3,
"selected": false,
"text": "/*\n-- ============================================================================\n-- Purpose: Performs a cascading hard-delete.\n-- Not for use on an active transactional database- it holds locks for too long.\n-- (http://stackoverflow.com/questions/116968/in-sql-server-2005-can-i-do-a-cascade-delete-without-setting-the-property-on-my)\n-- eg:\nexec dbo.hp_Common_Delete 'tblConsumer', 'Surname = ''TestDxOverdueOneReviewWm''', 1\n-- ============================================================================\n*/\ncreate proc [dbo].[hp_Common_Delete]\n(\n @TableName sysname, \n @Where nvarchar(4000), -- Shouldn't include 'where' keyword, e.g. Surname = 'smith', NOT where Surname = 'smith'\n @IsDebug bit = 0\n)\nas\nset nocount on\n\nbegin try\n -- Prepare tables to store deletion criteria. \n -- #tmp_to_delete stores criteria that is tested for results before being added to #to_delete\n create table #to_delete\n (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(4000) not null,\n table_name sysname not null,\n processed bit not null default(0)\n )\n create table #tmp_to_delete \n (\n id int primary key identity(1,1), \n criteria nvarchar(4000) not null, \n table_name sysname not null\n )\n\n -- Open a transaction (it'll be a long one- don't use this on production!)\n -- We need a transaction around criteria generation because we only \n -- retain criteria that has rows in the db, and we don't want that to change under us.\n begin tran\n -- If the top-level table meets the deletion criteria, add it\n declare @Sql nvarchar(4000)\n set @Sql = 'if exists(select top(1) * from ' + @TableName + ' where ' + @Where + ') \n insert #to_delete (criteria, table_name) values (''' + replace(@Where, '''', '''''') + ''', ''' + @TableName + ''')'\n exec (@Sql)\n\n -- Loop over deletion table, walking foreign keys to generate delete targets\n declare @id int, @tmp_id int, @criteria nvarchar(4000), @new_criteria nvarchar(4000), @table_name sysname, @new_table_name sysname\n while exists(select 1 from #to_delete where processed = 0) \n begin\n -- Grab table/criteria to work on\n select top(1) @id = id, \n @criteria = criteria, \n @table_name = table_name \n from #to_delete \n where processed = 0 \n order by id desc\n\n -- Insert all immediate child tables into a temp table for processing\n insert #tmp_to_delete\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')',\n referencing_table.name\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n -- Loop on child table criteria, and insert them into delete table if they have records in the db\n select @tmp_id = max(id) from #tmp_to_delete\n while (@tmp_id >= 1)\n begin\n select @new_criteria = criteria, @new_table_name = table_name from #tmp_to_delete where id = @tmp_id\n set @Sql = 'if exists(select top(1) * from ' + @new_table_name + ' where ' + @new_criteria + ') \n insert #to_delete (criteria, table_name) values (''' + replace(@new_criteria, '''', '''''') + ''', ''' + @new_table_name + ''')'\n exec (@Sql)\n\n set @tmp_id = @tmp_id - 1\n end\n truncate table #tmp_to_delete\n\n -- Move to next record\n update #to_delete \n set processed = 1\n where id = @id\n end\n\n -- We have a list of all tables requiring deletion. Actually delete now.\n select @id = max(id) from #to_delete \n while (@id >= 1)\n begin\n select @criteria = criteria, @table_name = table_name from #to_delete where id = @id\n set @Sql = 'delete from [' + @table_name + '] where ' + @criteria\n if (@IsDebug = 1) print @Sql\n exec (@Sql)\n\n -- Next record\n set @id = @id - 1\n end\n commit\nend try\n\nbegin catch\n -- Any error results in a rollback of the entire job\n if (@@trancount > 0) rollback\n\n declare @message nvarchar(2047), @errorProcedure nvarchar(126), @errorMessage nvarchar(2048), @errorNumber int, @errorSeverity int, @errorState int, @errorLine int\n select @errorProcedure = isnull(error_procedure(), N'hp_Common_Delete'), \n @errorMessage = isnull(error_message(), N'hp_Common_Delete unable to determine error message'), \n @errorNumber = error_number(), @errorSeverity = error_severity(), @errorState = error_state(), @errorLine = error_line()\n\n -- Prepare error information as it would be output in SQL Mgt Studio\n declare @event nvarchar(2047)\n select @event = 'Msg ' + isnull(cast(@errorNumber as varchar), 'null') + \n ', Level ' + isnull(cast(@errorSeverity as varchar), 'null') + \n ', State ' + isnull(cast(@errorState as varchar), 'null') + \n ', Procedure ' + isnull(@errorProcedure, 'null') + \n ', Line ' + isnull(cast(@errorLine as varchar), 'null') + \n ': ' + isnull(@errorMessage, '@ErrorMessage null')\n print @event\n\n -- Re-raise error to ensure admin/job runners understand there was a failure\n raiserror(@errorMessage, @errorSeverity, @errorState)\nend catch\n"
},
{
"answer_id": 16877011,
"author": "Łukasz Nojek",
"author_id": 1454656,
"author_profile": "https://Stackoverflow.com/users/1454656",
"pm_score": 2,
"selected": false,
"text": "CREATE PROCEDURE usp_delete_cascade (\n@base_table_schema varchar(100),\n@base_table_name varchar(200),\n@base_criteria nvarchar(1000)\n)\nas begin\n\n -- Expects the name of a table, and a conditional for selecting rows\n -- within that table that you want deleted.\n -- Produces SQL that, when run, deletes all table rows referencing the ones\n -- you initially selected, cascading into any number of tables,\n -- without the need for \"ON DELETE CASCADE\".\n -- Does not appear to work with self-referencing tables, but it will\n -- delete everything beneath them.\n -- To make it easy on the server, put a \"GO\" statement between each line.\n\n declare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_schema varchar(100),\n table_name varchar(200) not null,\n processed bit not null,\n delete_sql varchar(1000)\n )\n\n insert into @to_delete (criteria, table_schema, table_name, processed) values (@base_criteria, @base_table_schema, @base_table_name, 0)\n\n declare @id int, @criteria nvarchar(1000), @table_name varchar(200), @table_schema varchar(100)\n while exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name, @table_schema = table_schema from @to_delete where processed = 0 order by id desc\n\n insert into @to_delete (criteria, table_schema, table_name, processed)\n select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_schema + '].[' + @table_name +'] where ' + @criteria + ')',\n schematable.name,\n referencing_table.name,\n 0\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.schemas schematable on referencing_table.schema_id = schematable.schema_id\n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n update @to_delete set\n processed = 1\n where id = @id\n end\n\n select 'print ''deleting from ' + table_name + '...''; delete from [' + table_schema + '].[' + table_name + '] where ' + criteria from @to_delete order by id desc\n\n DECLARE @commandText VARCHAR(8000), @triggerOn VARCHAR(8000), @triggerOff VARCHAR(8000)\n DECLARE curDeletes CURSOR FOR\n select\n 'DELETE FROM [' + table_schema + '].[' + table_name + '] WHERE ' + criteria,\n 'ALTER TABLE [' + table_schema + '].[' + table_name + '] DISABLE TRIGGER ALL',\n 'ALTER TABLE [' + table_schema + '].[' + table_name + '] ENABLE TRIGGER ALL'\n from @to_delete order by id desc\n\n OPEN curDeletes\n FETCH NEXT FROM curDeletes INTO @commandText, @triggerOff, @triggerOn\n\n WHILE(@@FETCH_STATUS=0)\n BEGIN\n EXEC (@triggerOff)\n EXEC (@commandText)\n EXEC (@triggerOn)\n FETCH NEXT FROM curDeletes INTO @commandText, @triggerOff, @triggerOn\n END\n CLOSE curDeletes\n DEALLOCATE curDeletes\nend\n"
},
{
"answer_id": 33266262,
"author": "Jason Zheng",
"author_id": 5472816,
"author_profile": "https://Stackoverflow.com/users/5472816",
"pm_score": 1,
"selected": false,
"text": "create procedure usp_delete_cascade (\n@TableName varchar(200), @Where nvarchar(1000)\n) as begin\n\ndeclare @to_delete table (\n id int identity(1, 1) primary key not null,\n criteria nvarchar(1000) not null,\n table_name varchar(200) not null,\n processed bit not null default(0),\n delete_sql varchar(1000)\n)\n DECLARE @MyCursor CURSOR\n\ndeclare @referencing_column_name varchar(1000)\ndeclare @referencing_table_name varchar(1000)\n declare @Sql nvarchar(4000)\ninsert into @to_delete (criteria, table_name) values ('', @TableName)\n\n\ndeclare @id int, @criteria nvarchar(1000), @table_name varchar(200)\nwhile exists(select 1 from @to_delete where processed = 0) begin\n select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc\n SET @MyCursor = CURSOR FAST_FORWARD\n FOR\n select referencing_column.name as column_name,\n referencing_table.name as table_name\n from sys.foreign_key_columns fk\n inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id \n and fk.parent_column_id = referencing_column.column_id \n inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id \n and fk.referenced_column_id = referenced_column.column_id \n inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id \n inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id \n inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id\n where referenced_table.name = @table_name\n and referencing_table.name != referenced_table.name\n\n OPEN @MyCursor\n FETCH NEXT FROM @MYCursor\n INTO @referencing_column_name, @referencing_table_name\n\n WHILE @@FETCH_STATUS = 0\n\n BEGIN\n PRINT @referencing_column_name\n PRINT @referencing_table_name\n update @to_delete set criteria = criteria + ' AND '+@table_name+'.'+@referencing_column_name+'='+ @referencing_table_name+'.'+@referencing_column_name\n where table_name = @referencing_table_name\n\n if(@@ROWCOUNT = 0)\n BEGIN\n --if(@id <> 1)\n --BEGIN\n insert into @to_delete (criteria, table_name)\n VALUES( ' LEFT JOIN '+@table_name+' ON '+@table_name+'.'+@referencing_column_name+'='+ @referencing_table_name+'.'+@referencing_column_name+ @criteria,\n @referencing_table_name\n )\n --END\n --ELSE\n --BEGIN\n --insert into @to_delete (criteria, table_name)\n --VALUES( ' LEFT JOIN '+@table_name+' ON '+@table_name+'.'+@referencing_column_name+'='+ @referencing_table_name+'.'+@referencing_column_name,\n --@referencing_table_name\n --)\n --END\n END\n FETCH NEXT FROM @MYCursor\n INTO @referencing_column_name, @referencing_table_name\n END\n\n\n CLOSE @MyCursor \n DEALLOCATE @MyCursor \n update @to_delete set\n processed = 1\n where id = @id\nend\n\n--select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc\n\n--select id, table_name, criteria, @Where from @to_delete order by id desc\n\nselect @id = max(id) from @to_delete\nwhile (@id >= 1)\nbegin\n select @criteria = criteria, @table_name = table_name from @to_delete where id = @id\n set @Sql = 'delete [' + @table_name + '] from [' + @table_name + '] ' + @criteria+' WHERE '+@Where\n exec (@Sql)\n PRINT @Sql\n\n -- Next record\n set @id = @id - 1\nend\nend\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10906/"
] |
116,978
|
<p>I'm trying to get started on what I'm hoping will be a relatively quick web application in Java, yet most of the frameworks I've tried (Apache Wicket, Liftweb) require so much set-up, configuration, and trying to wrap my head around Maven while getting the whole thing to play nice with Eclipse, that I spent the whole weekend just trying to get to the point where I write my first line of code!</p>
<p>Can anyone recommend a simple Java webapp framework that doesn't involve Maven, hideously complicated directory structures, or countless XML files that must be manually edited?</p>
|
[
{
"answer_id": 117535,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 6,
"selected": false,
"text": "web.xml <web-app>\n <servlet>\n <servlet-name>spring-dispatcher</servlet-name>\n <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>\n </servlet>\n\n <servlet-mapping>\n <servlet-name>spring-dispatcher</servlet-name>\n <url-pattern>/*</url-pattern>\n </servlet-mapping>\n</web-app>\n /WEB-INF/spring-dispatcher-servlet.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n xmlns:mvc=\"http://www.springframework.org/schema/mvc\" xmlns:context=\"http://www.springframework.org/schema/context\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"\n http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\n http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:component-scan base-package=\"com.acme.foo\" /> \n <mvc:annotation-driven />\n\n</beans>\n @Controller package com.acme.foo;\n\nimport java.util.logging.Logger;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.ModelMap;\nimport org.springframework.web.bind.annotation.ModelAttribute;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\n@RequestMapping(\"/person\")\npublic class PersonController {\n\n Logger logger = Logger.getAnonymousLogger();\n\n @RequestMapping(method = RequestMethod.GET)\n public String setupForm(ModelMap model) {\n model.addAttribute(\"person\", new Person());\n return \"details.jsp\";\n }\n\n @RequestMapping(method = RequestMethod.POST)\n public String processForm(@ModelAttribute(\"person\") Person person) {\n logger.info(person.getId());\n logger.info(person.getName());\n logger.info(person.getSurname());\n return \"success.jsp\";\n }\n}\n details.jsp <%@ taglib uri=\"http://www.springframework.org/tags/form\" prefix=\"form\"%>\n<form:form commandName=\"person\">\n<table>\n <tr>\n <td>Id:</td>\n <td><form:input path=\"id\" /></td>\n </tr>\n <tr>\n <td>Name:</td>\n <td><form:input path=\"name\" /></td>\n </tr>\n <tr>\n <td>Surname:</td>\n <td><form:input path=\"surname\" /></td>\n </tr>\n <tr>\n <td colspan=\"2\"><input type=\"submit\" value=\"Save Changes\" /></td>\n </tr>\n</table>\n</form:form>\n"
},
{
"answer_id": 15033764,
"author": "Janus Troelsen",
"author_id": 309483,
"author_profile": "https://Stackoverflow.com/users/309483",
"pm_score": 0,
"selected": false,
"text": "wget --quiet --recursive --no-parent --accept=java --no-directories --no-host-directories \"http://www.fastcgi.com/devkit/java/\" mkdir -p com/fastcgi mv *.java com/fastcgi == <= echo -e \"175c\\nif (count <= 0) {\\n.\\nw\\nn\\nq\" | ed -s com/fastcgi/FCGIInputStream.java TinyFCGI.java javac **/*.java ** zsh java -DFCGI_PORT=9884 TinyFCGI mod_proxy_fcgi sudo a2enmod proxy_fcgi /etc/apache2/conf-enabled/your_site.conf sudo apache2ctl restart http://localhost/your_site TinyFCGI.java import com.fastcgi.FCGIInterface;\nimport java.io.*;\nimport static java.lang.System.out;\n\nclass TinyFCGI {\n public static void main (String args[]) {\n int count = 0;\n FCGIInterface fcgiinterface = new FCGIInterface();\n while(fcgiinterface.FCGIaccept() >= 0) {\n count++;\n out.println(\"Content-type: text/html\\n\\n\");\n out.println(\"<html>\");\n out.println(\n \"<head><TITLE>FastCGI-Hello Java stdio</TITLE></head>\");\n out.println(\"<body>\");\n out.println(\"<H3>FastCGI-HelloJava stdio</H3>\");\n out.println(\"request number \" + count +\n \" running on host \"\n + System.getProperty(\"SERVER_NAME\"));\n out.println(\"</body>\");\n out.println(\"</html>\");\n }\n }\n}\n your_site.conf <Location /your_site>\n ProxyPass fcgi://localhost:9884/\n</Location>\n $ ./wrk -t1 -c100 -r10000 http://localhost/your_site \nMaking 10000 requests to http://localhost/your_site\n 1 threads and 100 connections\n Thread Stats Avg Stdev Max +/- Stdev\n Latency 3.58s 13.42s 1.06m 94.42%\n Req/Sec 0.00 0.00 0.00 100.00%\n 10000 requests in 1.42m, 3.23MB read\n Socket errors: connect 0, read 861, write 0, timeout 2763\n Non-2xx or 3xx responses: 71\nRequests/sec: 117.03\nTransfer/sec: 38.70KB\n $ ab -n 10000 -c 100 localhost:8800/your_site\nConcurrency Level: 100\nTime taken for tests: 12.640 seconds\nComplete requests: 10000\nFailed requests: 0\nWrite errors: 0\nTotal transferred: 3180000 bytes\nHTML transferred: 1640000 bytes\nRequests per second: 791.11 [#/sec] (mean)\nTime per request: 126.404 [ms] (mean)\nTime per request: 1.264 [ms] (mean, across all concurrent requests)\nTransfer rate: 245.68 [Kbytes/sec] received\n $ siege -r 10000 -c 100 \"http://localhost:8800/your_site\"\n** SIEGE 2.70\n** Preparing 100 concurrent users for battle.\nThe server is now under siege...^C\nLifting the server siege... done.\nTransactions: 89547 hits\nAvailability: 100.00 %\nElapsed time: 447.93 secs\nData transferred: 11.97 MB\nResponse time: 0.00 secs\nTransaction rate: 199.91 trans/sec\nThroughput: 0.03 MB/sec\nConcurrency: 0.56\nSuccessful transactions: 89547\nFailed transactions: 0\nLongest transaction: 0.08\nShortest transaction: 0.00\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050/"
] |
116,988
|
<p>I have a number of data classes representing various entities. </p>
<p>Which is better: writing a generic class (say, to print or output XML) using generics and interfaces, or writing a separate class to deal with each data class?</p>
<p>Is there a performance benefit or any other benefit (other than it saving me the time of writing separate classes)?</p>
|
[
{
"answer_id": 118128,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 2,
"selected": false,
"text": "ArrayList listOfNames = new ArrayList();\nList<NameType> listOfNames = new List<NameType>();\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/116988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5648/"
] |
117,006
|
<p>In git, it is up to each user to specify the correct author in their local git config file. When they push to a centralized bare repository, the commit messages on the repository will have the author names that they used when committing to their own repository.</p>
<p>Is there a way enforce that a set of known authors for commits are used? The "central" repository will be accessible via ssh.</p>
<p>I know that this is complicated by the fact that some people may be pushing commits that were made by others. Of course, you should also only allow people you trust to push to your repositories, but it would be great if there was a way to prevent user error here.</p>
<p>Is there a simple solution to this problem in git? </p>
|
[
{
"answer_id": 641979,
"author": "Anders Waldenborg",
"author_id": 24082,
"author_profile": "https://Stackoverflow.com/users/24082",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\n#\n# This pre-receive hooks checks that all new commit objects\n# have authors and emails with matching entries in the files\n# valid-emails.txt and valid-names.txt respectively.\n#\n# The valid-{emails,names}.txt files should contain one pattern per\n# line, e.g:\n#\n# ^.*@0x63.nu$\n# ^allowed@example.com$\n#\n# To just ensure names are just letters the following pattern\n# could be used in valid-names.txt:\n# ^[a-zA-Z ]*$\n#\n\n\nNOREV=0000000000000000000000000000000000000000\n\nwhile read oldsha newsha refname ; do\n # deleting is always safe\n if [[ $newsha == $NOREV ]]; then\n continue\n fi\n\n # make log argument be \"..$newsha\" when creating new branch\n if [[ $oldsha == $NOREV ]]; then\n revs=$newsha\n else\n revs=$oldsha..$newsha\n fi\n echo $revs\n git log --pretty=format:\"%h %ae %an%n\" $revs | while read sha email name; do\n if [[ ! $sha ]]; then\n continue\n fi\n grep -q -f valid-emails.txt <<<\"$email\" || {\n echo \"Email address '$email' in commit $sha not registred when updating $refname\"\n exit 1\n }\n grep -q -f valid-names.txt <<<\"$name\" || {\n echo \"Name '$name' in commit $sha not registred when updating $refname\"\n exit 1\n }\n done\ndone\n"
},
{
"answer_id": 642182,
"author": "dsvensson",
"author_id": 5962,
"author_profile": "https://Stackoverflow.com/users/5962",
"pm_score": 4,
"selected": true,
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport subprocess\nfrom itertools import islice, izip\nimport sys\n\nold, new, branch = sys.stdin.read().split()\n\nauthors = {\n \"John Doe\": \"john.doe@example.com\"\n}\n\nproc = subprocess.Popen([\"git\", \"rev-list\", \"--pretty=format:%an%n%ae%n\", \"%s..%s\" % (old, new)], stdout=subprocess.PIPE)\ndata = [line.strip() for line in proc.stdout.readlines() if line.strip()]\n\ndef print_error(commit, author, email, message):\n print \"*\" * 80\n print \"ERROR: Unknown Author!\"\n print \"-\" * 80\n proc = subprocess.Popen([\"git\", \"rev-list\", \"--max-count=1\", \"--pretty=short\", commit], stdout=subprocess.PIPE)\n print proc.stdout.read().strip()\n print \"*\" * 80\n raise SystemExit(1)\n\nfor commit, author, email in izip(islice(data, 0, None, 3), islice(data, 1, None, 3), islice(data, 2, None, 3)):\n _, commit_hash = commit.split()\n if not author in authors:\n print_error(commit_hash, author, email, \"Unknown Author\")\n elif authors[author] != email:\n print_error(commit_hash, author, email, \"Unknown Email\")\n"
},
{
"answer_id": 36801917,
"author": "mrts",
"author_id": 258772,
"author_profile": "https://Stackoverflow.com/users/258772",
"pm_score": 2,
"selected": false,
"text": "from __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nimport os\nimport subprocess\nimport urllib2\nimport json\nimport contextlib\nimport codecs\nfrom itertools import islice, izip\n\nGITLAB_SERVER = 'https://localhost'\nGITLAB_TOKEN = 'SECRET'\nGITLAB_GROUP = 4\nEMAIL_DOMAIN = 'example.com'\n\ndef main():\n commits = get_commits_from_push()\n authors = get_gitlab_group_members()\n for commit, author, email in commits:\n if author not in authors:\n die('Unknown author', author, commit, authors)\n if email != authors[author]:\n die('Unknown email', email, commit, authors)\n\ndef get_commits_from_push():\n old, new, branch = sys.stdin.read().split()\n rev_format = '--pretty=format:%an%n%ae'\n command = ['git', 'rev-list', rev_format, '{0}..{1}'.format(old, new)]\n # branch delete, let it through\n if new == '0000000000000000000000000000000000000000':\n sys.exit(0)\n # new branch\n if old == '0000000000000000000000000000000000000000':\n command = ['git', 'rev-list', rev_format, new, '--not', '--branches=*']\n output = subprocess.check_output(command)\n commits = [line.strip() for line in unicode(output, 'utf-8').split('\\n') if line.strip()]\n return izip(islice(commits, 0, None, 3),\n islice(commits, 1, None, 3),\n islice(commits, 2, None, 3))\n\ndef get_gitlab_group_members():\n url = '{0}/api/v3/groups/{1}/members'.format(GITLAB_SERVER, GITLAB_GROUP)\n headers = {'PRIVATE-TOKEN': GITLAB_TOKEN}\n request = urllib2.Request(url, None, headers)\n with contextlib.closing(urllib2.urlopen(request)) as response:\n members = json.load(response)\n return dict((member['name'], '{}@{}'.format(member['username'], EMAIL_DOMAIN))\n for member in members)\n\ndef die(reason, invalid_value, commit, authors):\n message = []\n message.append('*' * 80)\n message.append(\"ERROR: {0} '{1}' in {2}\"\n .format(reason, invalid_value, commit))\n message.append('-' * 80)\n message.append('Allowed authors and emails:')\n print('\\n'.join(message), file=sys.stderr)\n for name, email in authors.items():\n print(u\" '{0} <{1}>'\".format(name, email), file=sys.stderr)\n sys.exit(1)\n\ndef set_locale(stream):\n return codecs.getwriter('utf-8')(stream)\n\nif __name__ == '__main__':\n # avoid Unicode errors in output\n sys.stdout = set_locale(sys.stdout)\n sys.stderr = set_locale(sys.stderr)\n\n # you may want to skip HTTPS certificate validation:\n # import ssl\n # if hasattr(ssl, '_create_unverified_context'):\n # ssl._create_default_https_context = ssl._create_unverified_context\n\n main()\n get_gitlab_group_members()"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
117,007
|
<p>I have some WCF methods that are used to transmit information from a server application to a website frontend for use in binding. I'm sending the result as an XElement that is a root of an XML tree containing the data I want to bind against.</p>
<p>I'd like to create some tests that examine the data and ensure it comes across as expected. </p>
<p>My current thinking is this: Every method that returns an XElement tree has a corresponding schema (.XSD) file. This file is included within the assembly that contains my WCF classes as an embedded resource.</p>
<p>Tests call the method on these methods and compares the result against these embedded schemas.</p>
<p>Is this a good idea? If not, what other ways can I use to provide a "guarantee" of what kind of XML a method will return?</p>
<p>If it is, how do you validate an XElement against a schema? And how can I get that schema from the assembly it's embedded in?</p>
|
[
{
"answer_id": 117217,
"author": "user19264",
"author_id": 19264,
"author_profile": "https://Stackoverflow.com/users/19264",
"pm_score": 5,
"selected": true,
"text": "String xsd =\n@\"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>\n <xsd:element name='root'>\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name='child1' minOccurs='1' maxOccurs='1'>\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name='grandchild1' minOccurs='1' maxOccurs='1'/>\n <xsd:element name='grandchild2' minOccurs='1' maxOccurs='2'/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n </xsd:schema>\";\nString xml = @\"<?xml version='1.0'?>\n<root>\n <child1>\n <grandchild1>alpha</grandchild1>\n <grandchild2>beta</grandchild2>\n </child1>\n</root>\";\nXmlSchemaSet schemas = new XmlSchemaSet();\nschemas.Add(\"\", XmlReader.Create(new StringReader(xsd)));\nXDocument doc = XDocument.Load(XmlReader.Create(new StringReader(xml)));\nBoolean errors = false;\ndoc.Validate(schemas, (sender, e) =>\n{\n Console.WriteLine(e.Message);\n errors = true;\n}, true);\nerrors = false;\nXElement child = doc.Element(\"root\").Element(\"child1\");\nchild.Validate(child.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>\n{\n Console.WriteLine(e.Message);\n errors = true;\n});\n Assembly assembly = Assembly.GetExecutingAssembly();\n// you can use reflector to get the full namespace of your embedded resource here\nStream stream = assembly.GetManifestResourceStream(\"AssemblyRootNamespace.Resources.XMLSchema.xsd\");\nXmlSchemaSet schemas = new XmlSchemaSet();\nschemas.Add(null, XmlReader.Create(stream));\n"
},
{
"answer_id": 120502,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 2,
"selected": false,
"text": "public class MyXElement : XElement \n{\n\n public MyXElement(XElement element)\n : base(element)\n { }\n\n public static bool TryParse(string xml, out MyXElement myElement)\n {\n XElement xmlAsXElement;\n\n try\n {\n xmlAsXElement = XElement.Parse(xml);\n }\n catch (XmlException)\n {\n myElement = null;\n return false;\n }\n\n // Use LINQ to check if xmlAsElement has correct nodes...\n }\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,014
|
<p>How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.</p>
|
[
{
"answer_id": 117047,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "import os;\nprint os.environ.get( \"USERNAME\" )\n"
},
{
"answer_id": 1992923,
"author": "Adam",
"author_id": 116819,
"author_profile": "https://Stackoverflow.com/users/116819",
"pm_score": 2,
"selected": false,
"text": "win32api.GetUserName()\n\nwin32api.GetUserNameEx(...) \n"
},
{
"answer_id": 23963670,
"author": "gaur_ab",
"author_id": 2761597,
"author_profile": "https://Stackoverflow.com/users/2761597",
"pm_score": -1,
"selected": false,
"text": "import os\nprint (os.getlogin())\n"
},
{
"answer_id": 24649918,
"author": "n611x007",
"author_id": 611007,
"author_profile": "https://Stackoverflow.com/users/611007",
"pm_score": 3,
"selected": false,
"text": "import getpass\ngetpass.getuser()\n getenv"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,041
|
<p>On our intranet site, we have various MS Office documents linked. When I click on a Word, Excel or PowerPoint file, Firefox gives me the option to Open, Save or Cancel. When I click on Open, the appropriate app is launched and the file is loaded. This is perfect. But for some reason, when I click on a linked Visio file, I only get the option to Save, which is inconvenient.</p>
<p>I know that Firefox knows the linked file is a Visio file because it tells me so in the dialog box: "You have chosen to open example.vsd which is a: Microsoft Visio Drawing".</p>
<p>How can I make Firefox launch Visio when I click on a linked Visio file?</p>
<p>Update:
Firefox is not launching Visio when I click on a linked Visio file because the web server does not identify the content-type correctly. It identifies the Visio file as application/octet-stream instead of application/x-visio. (Thanks Grant Wagner.) This explains why it doesn't work. And in my case, I may be able to get the Apache config file changed, but this is not certain.</p>
<p>However, I would love to know if there is a way to configure Firefox itself to launch Visio based on some other criteria, like file name extension. This way I can open Visio files even if I don't have access to the Apache configuration.</p>
|
[
{
"answer_id": 117515,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 1,
"selected": false,
"text": "application/octet-stream application/octet-stream application/x-visio"
},
{
"answer_id": 2861953,
"author": "theinterwebthingy",
"author_id": 344586,
"author_profile": "https://Stackoverflow.com/users/344586",
"pm_score": 1,
"selected": false,
"text": "<RDF:li RDF:resource=\"urn:mimetype:application/vnd.visio\"/>\n\n<RDF:Description RDF:about=\"urn:mimetype:externalApplication:application/vnd.visio\"\n NC:prettyName=\"VISIO.EXE\"\n NC:path=\"FULL PATH TO YOUR VISIO\\VISIO.EXE\" />\n\n<RDF:Description RDF:about=\"urn:mimetype:application/vnd.visio\"\n NC:value=\"application/vnd.visio\"\n NC:editable=\"true\"\n NC:fileExtensions=\"vsd\"\n NC:description=\"Microsoft Visio Drawing\">\n<NC:handlerProp RDF:resource=\"urn:mimetype:handler:application/vnd.visio\"/>\n</RDF:Description>\n<RDF:Description RDF:about=\"urn:mimetype:handler:application/vnd.visio\"\n NC:alwaysAsk=\"false\">\n<NC:externalApplication RDF:resource=\"urn:mimetype:externalApplication:application/vnd.visio\"/>\n<NC:possibleApplication RDF:resource=\"urn:handler:local:FULL PATH TO YOUR VISIO\\VISIO.EXE\"/>\n</RDF:Description>\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,108
|
<p>We log values and we only log them once in a table. When we add values to the table we have to do a look up everytime to see if it needs to insert the value or just grab the id. We have an index on the table (not on the primary key) but there are about 350,000 rows (so it is taking 10 seconds to do 10 of these values). </p>
<p>So either </p>
<ul>
<li>We figure out a way to optimize it </li>
<li>Strip it this feature out or </li>
<li>Do something completely different when logging these values.</li>
</ul>
|
[
{
"answer_id": 117425,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "try:\n UPDATE log SET blah blah blah WHERE key = key;\nexcept Missing Key:\n INSERT INTO log(...) VALUES(...);\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] |
117,110
|
<p>I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?</p>
|
[
{
"answer_id": 117140,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "plugins::v1::function\n"
},
{
"answer_id": 117145,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": true,
"text": "System.Data System.Data.SqlClient System.Data.OleDbClient"
},
{
"answer_id": 117182,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 0,
"selected": false,
"text": "namespace"
},
{
"answer_id": 117207,
"author": "Justin Rudd",
"author_id": 12968,
"author_profile": "https://Stackoverflow.com/users/12968",
"pm_score": 0,
"selected": false,
"text": "boost::this_thread::get_id()\nboost::this_thread::interruption_requested()\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15054/"
] |
117,127
|
<p>Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags!</p>
<p><strong>The Problem</strong></p>
<p>I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can describe it much better with snippets than words.</p>
<pre><code>## File 1
def f1(): print "go f1!"
class C1(object):
def do_eval(self,x): # maybe this should be do_evil, given what happens
print "evaling"
eval(x)
eval(x,globals(),locals())
</code></pre>
<p>Then run this code from an iteractive session, there there will be lots of <code>NameErrors</code></p>
<pre><code>## interactive
class C2(object):
def do_eval(self,x): # maybe this should be do_evil, given what happens
print "evaling"
eval(x)
eval(x,globals(),locals())
def f2():
print "go f2!"
from file1 import C1
import file1
C1().do_eval('file1.f1()')
C1().do_eval('f1()')
C1().do_eval('f2()')
file1.C1().do_eval('file1.f1()')
file1.C1().do_eval('f1()')
file1.C1().do_eval('f2()')
C2().do_eval('f2()')
C2().do_eval('file1.f1()')
C2().do_eval('f1()')
</code></pre>
<p>Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely? </p>
|
[
{
"answer_id": 117433,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 3,
"selected": true,
"text": "C1 >>> class C1(object):\n>>> def eval(self, x):\n>>> x()\n>>>\n>>> def f2(): print \"go f2\"\n>>> c = C1()\n>>> c.eval(f2)\ngo f2\n ## File 1\ndef f1(): print \"go f1!\"\n\nclass C1(object):\n def do_eval(self, x, e_globals = globals(), e_locals = locals()):\n eval(x, e_globals, e_locals)\n >>> def f2():\n>>> print \"go f2!\"\n>>> from file1 import * # 1\n>>> C1().do_eval(\"f2()\") # 2\nNameError: name 'f2' is not defined\n\n>>> C1().do_eval(\"f2()\", globals(), locals()) #3\ngo f2!\n>>> C1().do_eval(\"f1()\", globals(), locals()) #4\ngo f1!\n file1 f2 file1 NameError f1 eval"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
] |
117,129
|
<p>Traditionalist argue that stored procedures provide better security than if you use a Object Relational Mapping (ORM) framework such as NHibernate. </p>
<p>To counter that argument what are some approaches that can be used with NHibernate to ensure that proper security is in place (for example, preventing sql injection, etc.)?</p>
<p>(<em>Please provide only one approach per answer</em>)</p>
|
[
{
"answer_id": 119136,
"author": "scott.caligan",
"author_id": 14814,
"author_profile": "https://Stackoverflow.com/users/14814",
"pm_score": 3,
"selected": false,
"text": "<connectionStrings> connection.connection_string_name connection.connection_string aspnet_regiis <connectionStrings>"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
117,135
|
<p>What resources have to be manually cleaned up in <em>C#</em> and what are the consequences of not doing so?</p>
<p>For example, say I have the following code:</p>
<pre><code>myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
// Use Brush
</code></pre>
<p>If I don't clean up the brush using the dispose method, I'm assuming the garbage collector frees the memory used at program termination? Is this correct?</p>
<p>What other resources do I need to manually clean up?</p>
|
[
{
"answer_id": 117164,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 3,
"selected": false,
"text": "Dispose using using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))\n{\n // use myBrush\n}\n System.Drawing.Brush"
},
{
"answer_id": 117184,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 3,
"selected": false,
"text": "using using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))\n{\n // use myBrush\n}\n"
},
{
"answer_id": 117194,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "using"
},
{
"answer_id": 117237,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": false,
"text": "using (new DisposableThing...\n{\n ...\n}\n class MyClass : IDisposable\n{\n private IDisposable disposableThing;\n\n public void DoStuffThatRequiresHavingAReferenceToDisposableThing() { ... }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n //etc... (see IDisposable on msdn)\n"
},
{
"answer_id": 117652,
"author": "lotsoffreetime",
"author_id": 18248,
"author_profile": "https://Stackoverflow.com/users/18248",
"pm_score": 1,
"selected": false,
"text": "MemoryStream ms = new MemoryStream().Dispose\n using(MemoryStream ms = new MemoryStream())\n{\n ...\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
117,150
|
<p>I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing <code>:WQ</code> instead of <code>:wq</code>. (On a German keyboard, you have to press <kbd>Shift</kbd> to get the colon <code>:</code>.) Vim will then complain that <code>WQ</code> is <code>Not an editor command</code>.</p>
<p>Is there some way to make <code>W</code> and <code>Q</code> editor commands?</p>
|
[
{
"answer_id": 117221,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 7,
"selected": true,
"text": " :command WQ wq\n :command Wq wq\n :command W w\n :command Q q\n :help command"
},
{
"answer_id": 119821,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 4,
"selected": false,
"text": ":cmap WQ wq\n cmap h tab help\n .vimrc cnoreabbrev <expr> h getcmdtype() == \":\" && getcmdline() == \"h\" ? \"tab h\" : \"h\"\n"
},
{
"answer_id": 4125577,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": false,
"text": ":ca WQ wq\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7498/"
] |
117,171
|
<p>When programming by contract a function or method first checks whether its preconditions are fulfilled, before starting to work on its responsibilities, right? The two most prominent ways to do these checks are by <code>assert</code> and by <code>exception</code>. </p>
<ol>
<li>assert fails only in debug mode. To make sure it is crucial to (unit) test all separate contract preconditions to see whether they actually fail.</li>
<li>exception fails in debug and release mode. This has the benefit that tested debug behavior is identical to release behavior, but it incurs a runtime performance penalty.</li>
</ol>
<p>Which one do you think is preferable?</p>
<p>See releated question <a href="https://stackoverflow.com/questions/419406/are-assertions-good">here</a></p>
|
[
{
"answer_id": 117328,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": -1,
"selected": false,
"text": "assert(value>0);\nif(value<=0) throw new ArgumentOutOfRangeException(\"value\");\n//do stuff\n"
},
{
"answer_id": 117729,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 0,
"selected": false,
"text": "#ifdef DEBUG\n#define RETURN_IF_FAIL(expr) do { \\\n if (!(expr)) \\\n { \\\n fprintf(stderr, \\\n \"file %s: line %d (%s): precondition `%s' failed.\", \\\n __FILE__, \\\n __LINE__, \\\n __PRETTY_FUNCTION__, \\\n #expr); \\\n ::print_stack_trace(2); \\\n return; \\\n }; } while(0)\n#define RETURN_VAL_IF_FAIL(expr, val) do { \\\n if (!(expr)) \\\n { \\\n fprintf(stderr, \\\n \"file %s: line %d (%s): precondition `%s' failed.\", \\\n __FILE__, \\\n __LINE__, \\\n __PRETTY_FUNCTION__, \\\n #expr); \\\n ::print_stack_trace(2); \\\n return val; \\\n }; } while(0)\n#else\n#define RETURN_IF_FAIL(expr)\n#define RETURN_VAL_IF_FAIL(expr, val)\n#endif\n char *doSomething(char *ptr)\n{\n RETURN_VAL_IF_FAIL(ptr != NULL, NULL); // same as assert(ptr != NULL), but returns NULL if it fails.\n // Goes away when debug off.\n\n if( ptr != NULL )\n {\n ...\n }\n\n return ptr;\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
] |
117,173
|
<p><strong>I do not currently have this issue</strong>, but you never know, and thought experiments are always fun.</p>
<p><strong>Ignoring the obvious problems that you would have to have with your architecture to even be attempting this</strong>, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.:</p>
<pre><code>WidgetMaker.SetAlignment(57);
contactForm["Title"] = txtTitle.Text;
Casserole.Season(true, false);
((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true;
</code></pre>
<p>Multiplied by a hundred. Some of these might work, others might go badly wrong. What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code.</p>
<p>How would you attempt to tackle this problem?</p>
|
[
{
"answer_id": 117202,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 3,
"selected": false,
"text": "On Error Resume Next On Error Resume Next"
},
{
"answer_id": 117235,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 5,
"selected": false,
"text": "AdjustFormWidgets();\nSetContactTitle(txtTitle.Text);\nSeasonCasserole();\n"
},
{
"answer_id": 117268,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 3,
"selected": false,
"text": "#define ATTEMPT(x) try { x; } catch (...) { }\n// ...\nATTEMPT(WidgetMaker.SetAlignment(57));\nATTEMPT(contactForm[\"Title\"] = txtTitle.Text);\nATTEMPT(Casserole.Season(true, false));\nATTEMPT(((RecordKeeper)Session[\"CasseroleTracker\"]).Seasoned = true);\n"
},
{
"answer_id": 117370,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "Using (New InstEvent)\n<series of statements> \nEnd Using\n"
},
{
"answer_id": 117737,
"author": "Lost Plugin Writer",
"author_id": 7425,
"author_profile": "https://Stackoverflow.com/users/7425",
"pm_score": 6,
"selected": false,
"text": "public delegate void VoidDelegate();\n\npublic static class Utils\n{\n public static void Try(VoidDelegate v) {\n try {\n v();\n }\n catch {}\n }\n}\n\nUtils.Try( () => WidgetMaker.SetAlignment(57) );\nUtils.Try( () => contactForm[\"Title\"] = txtTitle.Text );\nUtils.Try( () => Casserole.Season(true, false) );\nUtils.Try( () => ((RecordKeeper)Session[\"CasseroleTracker\"]).Seasoned = true );\n"
},
{
"answer_id": 118742,
"author": "Christopher Elliott",
"author_id": 5072,
"author_profile": "https://Stackoverflow.com/users/5072",
"pm_score": 2,
"selected": false,
"text": "Sub Main()\n On Error Resume Next\n\n Dim i As Integer = 0\n\n Dim y As Integer = CInt(5 / i)\n\n\nEnd Sub\n public static void Main()\n{\n // This item is obfuscated and can not be translated.\n int VB$ResumeTarget;\n try\n {\n int VB$CurrentStatement;\n Label_0001:\n ProjectData.ClearProjectError();\n int VB$ActiveHandler = -2;\n Label_0009:\n VB$CurrentStatement = 2;\n int i = 0;\n Label_000E:\n VB$CurrentStatement = 3;\n int y = (int) Math.Round((double) (5.0 / ((double) i)));\n goto Label_008F;\n Label_0029:\n VB$ResumeTarget = 0;\n switch ((VB$ResumeTarget + 1))\n {\n case 1:\n goto Label_0001;\n\n case 2:\n goto Label_0009;\n\n case 3:\n goto Label_000E;\n\n case 4:\n goto Label_008F;\n\n default:\n goto Label_0084;\n }\n Label_0049:\n VB$ResumeTarget = VB$CurrentStatement;\n switch (((VB$ActiveHandler > -2) ? VB$ActiveHandler : 1))\n {\n case 0:\n goto Label_0084;\n\n case 1:\n goto Label_0029;\n }\n }\n catch (object obj1) when (?)\n {\n ProjectData.SetProjectError((Exception) obj1);\n goto Label_0049;\n }\nLabel_0084:\n throw ProjectData.CreateProjectError(-2146828237);\nLabel_008F:\n if (VB$ResumeTarget != 0)\n {\n ProjectData.ClearProjectError();\n }\n}\n"
},
{
"answer_id": 122140,
"author": "b w",
"author_id": 4126,
"author_profile": "https://Stackoverflow.com/users/4126",
"pm_score": 1,
"selected": false,
"text": "try-catch switch-goto try catch"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
117,189
|
<p>I have a search form with a query builder. The builder is activated by a button. Something like this</p>
<pre><code><h:form id="search_form">
<h:outputLabel for="expression" value="Expression"/>
<h:inputText id="expression" required="true" value="#{searcher.expression}"/>
<button onclick="openBuilder(); return false;">Open Builder</button>
<h:commandButton value="Search" action="#{searcher.search}"/>
</h:form>
</code></pre>
<p>The result is HTML that has both a <code><button/></code> and an <code><input type="submit"/></code> in the form. If the user enters a string into the expression field and hits the enter key rather than clicking the submit button, the query builder is displayed when the expected behavior is that the search be submitted. What gives?</p>
|
[
{
"answer_id": 117338,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 1,
"selected": false,
"text": " function KeyDownHandler(event)\n {\n // process only the Enter key\n if (event.keyCode == 13)\n {\n // cancel the default submit\n event.returnValue=false;\n event.cancel = true;\n // submit the form by programmatically clicking the specified button\n document.getElementById('searchButtonId').click();\n }\n }\n"
},
{
"answer_id": 118570,
"author": "user13229",
"author_id": 13229,
"author_profile": "https://Stackoverflow.com/users/13229",
"pm_score": 0,
"selected": false,
"text": "<input type=\"text\" name=\"bogusField\" style=\"display: none;\" />"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
117,211
|
<p>I have a Tix.ComboBox with an editable text field. How do I force the variable holding the value for the text to update?</p>
<p>Let me give a more concrete explanation. I have a combo box and a button. When I click the button, it pops up a message box with the value of the combo box. Let's say the combo box text field currently has the value "thing1". If I type "new" into the box and then click on the button with my mouse, it will pops up the message "thing1". If I type "new" in the box and then tab focus away from the combo box and then click the button the pop up message says "new".</p>
<p>Ho do I force the combo box to update it's value to new without requiring that I tab away from the combo box?</p>
<p>I have included sample code.</p>
<pre><code>import Tix
import tkMessageBox
class App(object):
def __init__(self, window):
window.winfo_toplevel().wm_title("test")
self.window = window
self.combo = Tix.ComboBox(window)
self.combo.insert(Tix.END, 'thing1')
self.combo.insert(Tix.END, 'thing2')
self.combo.entry['state'] = "normal"
self.combo['editable'] = True
self.combo.pack()
button = Tix.Button(window)
button['text'] = "Go"
button['command'] = self.go
button.pack()
def go(self):
tkMessageBox.showinfo('info', self.combo['value'])
if __name__ == '__main__':
root = Tix.Tk()
App(root)
root.mainloop()
</code></pre>
|
[
{
"answer_id": 117384,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 4,
"selected": true,
"text": "self.combo['selection']\n self.combo['value']\n"
},
{
"answer_id": 207117,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "self.combo['selection']\n self.combo['value']\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] |
117,226
|
<p>I have a <code>PHP</code> script that listens on a queue. Theoretically, it's never supposed to die. Is there something to check if it's still running? Something like <code>Ruby's God ( http://god.rubyforge.org/ )</code> for <code>PHP</code>?</p>
<p>God is language agnostic but it would be nice to have a solution that works on windows as well.</p>
|
[
{
"answer_id": 117287,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\nwhile [true]; do\n if ! pidof -x script.php;\n then\n php script.php &\n fi\ndone\n"
},
{
"answer_id": 121717,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": false,
"text": "php daemon.php 2>&1 | mail -s \"Daemon stopped\" you@example.org\n"
},
{
"answer_id": 122568,
"author": "Daniel Schierbeck",
"author_id": 20321,
"author_profile": "https://Stackoverflow.com/users/20321",
"pm_score": 0,
"selected": false,
"text": "php daemon.php | mail -s \"Daemon stopped\" you@example.org\n mail php daemon.php & mail -s \"Daemon stopped\" you@example.org\n"
},
{
"answer_id": 8465822,
"author": "Jay",
"author_id": 1092461,
"author_profile": "https://Stackoverflow.com/users/1092461",
"pm_score": 4,
"selected": false,
"text": "exec(\"ps -U #user# -u #user# u\", $output, $result);\nforeach ($output AS $line) if(strpos($line, \"test.php\")) echo \"found\";\n"
},
{
"answer_id": 32478281,
"author": "Justin Levene",
"author_id": 1938802,
"author_profile": "https://Stackoverflow.com/users/1938802",
"pm_score": 4,
"selected": false,
"text": "ps -C php -f\n $output = shell_exec('ps -C php -f');\nif (strpos($output, \"php my_script.php\")===false) { \n shell_exec('php my_script.php > /dev/null 2>&1 &');\n}\n"
},
{
"answer_id": 33761271,
"author": "Zvonimir Burić",
"author_id": 1895587,
"author_profile": "https://Stackoverflow.com/users/1895587",
"pm_score": 1,
"selected": false,
"text": "0 3 * * * /usr/bin/php -f /home/test/test.php my_special_cron\n <?php\n\nphp_sapi_name() == 'cli' || exit;\n\nif($argv[1]) {\n substr_count(shell_exec('ps -ax'), $argv[1]) < 3 || exit;\n}\n\n// your code here\n my-special-cron test.php system_send_emails sendEmails test.php system_create_orders orderExport"
},
{
"answer_id": 36348388,
"author": "Burak Kurkcu",
"author_id": 2517120,
"author_profile": "https://Stackoverflow.com/users/2517120",
"pm_score": 1,
"selected": false,
"text": "ps -C $daemonPath = \"FULL_PATH_TO_DAEMON\";\n$runningPhpProcessesOfDaemon = (int) shell_exec(\"ps aux | grep -c '[p]hp \".$daemonPath.\"'\");\nif ($runningPhpProcessesOfDaemon === 0) {\n shell_exec('php ' . $daemonPath . ' > /dev/null 2>&1 &');\n}\n grep -c '[p]hp ...' grep -c 'php ...' grep -c 'php ...'"
},
{
"answer_id": 39642531,
"author": "Jack Simth",
"author_id": 2640003,
"author_profile": "https://Stackoverflow.com/users/2640003",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\nphp test.php\n"
},
{
"answer_id": 40463579,
"author": "Kamaro",
"author_id": 2858817,
"author_profile": "https://Stackoverflow.com/users/2858817",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n clear\n date\n while true\n do\n php -f processEmails.php\n echo \"wait a little while for 5 secobds...\"; \n sleep 5\n done \n"
},
{
"answer_id": 59525734,
"author": "Dom DaFonte",
"author_id": 7506883,
"author_profile": "https://Stackoverflow.com/users/7506883",
"pm_score": 2,
"selected": false,
"text": "$runningScripts = shell_exec('ps -ef |grep '.strtolower($parameter).' |grep '.dirname(__FILE__).' |grep '.basename(__FILE__).' |grep -v grep |wc -l');\nif($runningScripts > 1){\n die();\n}\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
117,245
|
<p>I've always just FTPed files down from sites, edited them and put them back up when creating sites, but feel it's worth learning to do things properly.</p>
<p>I've just commited everything to a SVN repo, and have tried sshing into the server and checking out a tagged build, as well as updating that build using switch.</p>
<p>All good, but it's a lot lot slower than my current process.</p>
<p>What's the best way to set something like this up? Most of my time is just bug fixes or small changes rather than large rewrites, so I'm frequently updating things.</p>
|
[
{
"answer_id": 117271,
"author": "edgars",
"author_id": 6865,
"author_profile": "https://Stackoverflow.com/users/6865",
"pm_score": 2,
"selected": false,
"text": "svn update"
},
{
"answer_id": 122519,
"author": "Daniel Schierbeck",
"author_id": 20321,
"author_profile": "https://Stackoverflow.com/users/20321",
"pm_score": 2,
"selected": false,
"text": "svn update cap deploy"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
] |
117,248
|
<p>I have a number of tables that use the trigger/sequence column to simulate auto_increment on their primary keys which has worked great for some time.</p>
<p>In order to speed the time necessary to perform regression testing against software that uses the db, I create control files using some sample data, and added running of these to the build process.</p>
<p>This change is causing most of the tests to crash though as the testing process installs the schema from scratch, and the sequences are returning values that already exist in the tables. Is there any way to programtically say "Update sequences to max value in column" or do I need to write out a whole script by hand that updates all these sequences, or can I/should I change the trigger that substitutes the null value for the sequence to some how check this (though I think this might cause the mutating table problem)?</p>
|
[
{
"answer_id": 117360,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 2,
"selected": true,
"text": "SELECT 'CREATE SEQUENCE '||sequence_name||' START WITH '||last_number||';'\nFROM ALL_SEQUENCES\nWHERE OWNER = your_schema\n"
},
{
"answer_id": 142768,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 1,
"selected": false,
"text": "alter sequence MYSEQUENCE increment by 950 nocache;\nselect MYSEQUENCE_S.nextval from dual;\nalter sequence MYSEQUENCE increment by 1;\n"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
117,250
|
<p>For example, the standard division symbol '/' rounds to zero:</p>
<pre><code>>>> 4 / 100
0
</code></pre>
<p>However, I want it to return 0.04. What do I use?</p>
|
[
{
"answer_id": 117258,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": ">>> 4/100.0\n0.040000000000000001\n"
},
{
"answer_id": 117264,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": true,
"text": ">>> 4 / float(100)\n0.04\n>>> 4 / 100.0\n0.04\n >>> from __future__ import division\n>>> 4 / 100\n0.04\n -Qnew $ python -Qnew\n>>> 4 / 100\n0.04\n // -Qnew"
},
{
"answer_id": 117270,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 3,
"selected": false,
"text": "4.0/100.0\n from __future__ import division\n"
},
{
"answer_id": 117682,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 5,
"selected": false,
"text": ">>> 0.4/100.\n0.0040000000000000001\n >>> import decimal\n>>> decimal.Decimal('4') / decimal.Decimal('100')\nDecimal(\"0.04\")\n"
},
{
"answer_id": 117806,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": ">>> decimal.Decimal('4')/100\nDecimal(\"0.04\")\n"
},
{
"answer_id": 48145519,
"author": "Jai Narayan",
"author_id": 5622450,
"author_profile": "https://Stackoverflow.com/users/5622450",
"pm_score": 1,
"selected": false,
"text": "from __future__ import division\n\nprint(4/100)\nprint(4//100)\n"
},
{
"answer_id": 48924804,
"author": "T. Samuel",
"author_id": 8643901,
"author_profile": "https://Stackoverflow.com/users/8643901",
"pm_score": -1,
"selected": false,
"text": "from__future__ import division\n"
},
{
"answer_id": 51169141,
"author": "DaredevilRanon",
"author_id": 9946483,
"author_profile": "https://Stackoverflow.com/users/9946483",
"pm_score": 0,
"selected": false,
"text": "# Starting of the function\ndef divide(number_one, number_two, decimal_place = 4):\n quotient = number_one/number_two\n remainder = number_one % number_two\n if remainder != 0:\n quotient_str = str(quotient)\n for loop in range(0, decimal_place):\n if loop == 0:\n quotient_str += \".\"\n surplus_quotient = (remainder * 10) / number_two\n quotient_str += str(surplus_quotient)\n remainder = (remainder * 10) % number_two\n if remainder == 0:\n break\n return float(quotient_str)\n else:\n return quotient\n#Ending of the function\n\n# Calling back the above function\n# Structure : divide(<divident>, <divisor>, <decimal place(optional)>)\ndivide(1, 7, 10) # Output : 0.1428571428\n# OR\ndivide(1, 7) # Output : 0.1428\n divide(1, 7, 10) divide(1, 7)"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
117,262
|
<p>MySQL's explain output is pretty straightforward. PostgreSQL's is a little more complicated. I haven't been able to find a good resource that explains it either.</p>
<p>Can you describe what exactly explain is saying or at least point me in the direction of a good resource?</p>
|
[
{
"answer_id": 118122,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 5,
"selected": false,
"text": "EXPLAIN explain analyze\nselect a.attributeid, a.attributevalue, b.productid\nfrom orderitemattribute a, orderitem b\nwhere a.orderid = b.orderid\nand a.attributeid = 'display-album'\nand b.productid = 'ModernBook';\n\n------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n Merge Join (cost=125379.14..125775.12 rows=3311 width=29) (actual time=841.478..841.478 rows=0 loops=1)\n Merge Cond: (a.orderid = b.orderid)\n -> Sort (cost=109737.32..109881.89 rows=57828 width=23) (actual time=736.163..774.475 rows=16815 loops=1)\n Sort Key: a.orderid\n Sort Method: quicksort Memory: 1695kB\n -> Bitmap Heap Scan on orderitemattribute a (cost=1286.88..105163.27 rows=57828 width=23) (actual time=41.536..612.731 rows=16815 loops=1)\n Recheck Cond: ((attributeid)::text = 'display-album'::text)\n -> Bitmap Index Scan on (cost=0.00..1272.43 rows=57828 width=0) (actual time=25.033..25.033 rows=16815 loops=1)\n Index Cond: ((attributeid)::text = 'display-album'::text)\n -> Sort (cost=15641.81..15678.73 rows=14769 width=14) (actual time=14.471..16.898 rows=1109 loops=1)\n Sort Key: b.orderid\n Sort Method: quicksort Memory: 76kB\n -> Bitmap Heap Scan on orderitem b (cost=310.96..14619.03 rows=14769 width=14) (actual time=1.865..8.480 rows=1114 loops=1)\n Recheck Cond: ((productid)::text = 'ModernBook'::text)\n -> Bitmap Index Scan on id_orderitem_productid (cost=0.00..307.27 rows=14769 width=0) (actual time=1.431..1.431 rows=1114 loops=1)\n Index Cond: ((productid)::text = 'ModernBook'::text)\n Total runtime: 842.134 ms\n(17 rows)\n id_orderitem_productid orderitem orditematt_attributeid_idx orderitemattribute"
},
{
"answer_id": 35510927,
"author": "Mark E. Haase",
"author_id": 122763,
"author_profile": "https://Stackoverflow.com/users/122763",
"pm_score": 7,
"selected": false,
"text": "EXPLAIN EXPLAIN SELECT * FROM post LIMIT 50;\n\nLimit (cost=0.00..3.39 rows=50 width=422)\n -> Seq Scan on post (cost=0.00..15629.12 rows=230412 width=422)\n LIMIT cost=0.00..3.39 post cost=0.00..15629.12 EXPLAIN EXPLAIN ANALYZE LIMIT Seq Scan 3.39 15629.12 LIMIT EXPLAIN SELECT * FROM tenk1 WHERE unique1 < 100 AND unique2 > 9000 LIMIT 2; EXPLAIN LIMIT ORDER BY EXPLAIN SELECT * FROM post ORDER BY body LIMIT 50;\n\nLimit (cost=23283.24..23283.37 rows=50 width=422)\n -> Sort (cost=23283.24..23859.27 rows=230412 width=422)\n Sort Key: body\n -> Seq Scan on post (cost=0.00..15629.12 rows=230412 width=422)\n post 23283.24 23859.27 LIMIT 23283.24 LIMIT EXPLAIN LIMIT LIMIT EXPLAIN"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38359/"
] |
117,293
|
<p>How far do you go with <code>const</code>? Do you just make functions <code>const</code> when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter:</p>
<pre><code>void SetValue(const bool b) { my_val_ = b; }
</code></pre>
<p>Is that <code>const</code> actually useful? Personally I opt to use it extensively, including parameters, but in this case I wonder if it's worthwhile?</p>
<p>I was also surprised to learn that you can omit <code>const</code> from parameters in a function declaration but can include it in the function definition, e.g.:</p>
<p><strong>.h file</strong></p>
<pre><code>void func(int n, long l);
</code></pre>
<p><strong>.cpp file</strong></p>
<pre><code>void func(const int n, const long l)
</code></pre>
<p>Is there a reason for this? It seems a little unusual to me.</p>
|
[
{
"answer_id": 117308,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 9,
"selected": true,
"text": "const const const_iterator const"
},
{
"answer_id": 117311,
"author": "Asaf R",
"author_id": 6827,
"author_profile": "https://Stackoverflow.com/users/6827",
"pm_score": 3,
"selected": false,
"text": "void foo(int a);\n void foo(const int a);\n"
},
{
"answer_id": 117458,
"author": "Ben Straub",
"author_id": 1319,
"author_profile": "https://Stackoverflow.com/users/1319",
"pm_score": 7,
"selected": false,
"text": "int foo (int a);\nint foo (const int a);\n a foo const int foo (const BigStruct &a);\nint foo (const BigStruct *a);\n"
},
{
"answer_id": 117488,
"author": "Dan Hewett",
"author_id": 17975,
"author_profile": "https://Stackoverflow.com/users/17975",
"pm_score": 3,
"selected": false,
"text": "int SomeClass::GetValue() const {return m_internalValue;}\n const SomeClass* pSomeClass;\npSomeClass->GetValue();\n"
},
{
"answer_id": 117557,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 9,
"selected": false,
"text": "const const"
},
{
"answer_id": 117932,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 5,
"selected": false,
"text": "foo() = 42\n foo() == 42\n int& foo() { /* ... */ }\n const int& foo() { /* ... */ }\n"
},
{
"answer_id": 118117,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 3,
"selected": false,
"text": "void func(const int n, const long l) { /* ... */ }\n"
},
{
"answer_id": 120483,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 5,
"selected": false,
"text": "int i = 5 ; // i is a constant\n\nvar int i = 5 ; // i is a real variable\n"
},
{
"answer_id": 290101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "bool isZero(int number)\n{\n if (number = 0) // whoops, should be number == 0\n return true;\n else\n return false;\n}\n"
},
{
"answer_id": 11036371,
"author": "Adisak",
"author_id": 14904,
"author_profile": "https://Stackoverflow.com/users/14904",
"pm_score": 7,
"selected": false,
"text": "void mungerum(char * buffer, const char * mask, int count);\n\nvoid mungerum(char * const buffer, const char * const mask, const int count);\n char * const buffer #if FLEXIBLE_IMPLEMENTATION\n #define SUPERFLUOUS_CONST\n#else\n #define SUPERFLUOUS_CONST const\n#endif\n\nvoid bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source, SUPERFLUOUS_CONST int count);\n void bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source, SUPERFLUOUS_CONST int count)\n{\n // Will break if !FLEXIBLE_IMPLEMENTATION\n while(count--)\n {\n *dest++=*source++;\n }\n}\n\nvoid bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source, SUPERFLUOUS_CONST int count)\n{\n for(int i=0;i<count;i++)\n {\n dest[i]=source[i];\n }\n}\n inline void bytecopyWrapped(char * dest,\n const char *source, int count)\n{\n while(count--)\n {\n *dest++=*source++;\n }\n}\nvoid bytecopy(char * SUPERFLUOUS_CONST dest,\n const char *source,SUPERFLUOUS_CONST int count)\n{\n bytecopyWrapped(dest, source, count);\n}\n // Example of const only in definition, not declaration\nstruct foo { void test(int *pi); };\nvoid foo::test(int * const pi) { }\n struct foo\n{\n void test(int * const pi);\n};\n\nvoid foo::test(int *pi) // Look, the const in the definition is so superfluous I can ignore it here\n{\n pi++; // I promised in my definition I wouldn't modify this\n}\n struct llist\n{\n llist * next;\n};\n\nvoid walkllist(llist *plist)\n{\n llist *pnext;\n while(plist)\n {\n pnext=plist->next;\n walk(plist);\n plist=pnext; // This line wouldn't compile if plist was const\n }\n}\n\nvoid walkllist(llist * SUPERFLUOUS_CONST plist)\n{\n llist * pnotconst=plist;\n llist *pnext;\n while(pnotconst)\n {\n pnext=pnotconst->next;\n walk(pnotconst);\n pnotconst=pnext;\n }\n}\n"
},
{
"answer_id": 11622623,
"author": "user541686",
"author_id": 541686,
"author_profile": "https://Stackoverflow.com/users/541686",
"pm_score": 3,
"selected": false,
"text": "->* .* void foo(Bar *p) { if (++p->*member > 0) { ... } }\n void foo(Bar *p) { if (++(p->*member) > 0) { ... } }\n const Bar * p"
},
{
"answer_id": 29510533,
"author": "PavDub",
"author_id": 3840660,
"author_profile": "https://Stackoverflow.com/users/3840660",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nclass SharedBuffer {\nprivate:\n\n int fakeData;\n\n int const & Get_(int i) const\n {\n\n std::cout << \"Accessing buffer element\" << std::endl;\n return fakeData;\n\n }\n\npublic:\n\n int & operator[](int i)\n {\n\n Unique();\n return const_cast<int &>(Get_(i));\n\n }\n\n int const & operator[](int i) const\n {\n\n return Get_(i);\n\n }\n\n void Unique()\n {\n\n std::cout << \"Making buffer unique (expensive operation)\" << std::endl;\n\n }\n\n};\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid NonConstF(SharedBuffer x)\n{\n\n x[0] = 1;\n\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nvoid ConstF(const SharedBuffer x)\n{\n\n int q = x[0];\n\n}\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nint main()\n{\n\n SharedBuffer x;\n\n NonConstF(x);\n\n std::cout << std::endl;\n\n ConstF(x);\n\n return 0;\n\n}\n"
},
{
"answer_id": 44228229,
"author": "Paul Stearns",
"author_id": 2027333,
"author_profile": "https://Stackoverflow.com/users/2027333",
"pm_score": -1,
"selected": false,
"text": "typedef int (EE_STDCALL *Do_SomethingPtr)( int smfID, const char* cursor_name, const char* sql );\n Declare Function Do_Something Lib \"SomeOther.DLL\" (ByRef smfID As Integer, ByVal cursor_name As String, ByVal sql As String) As Integer\n"
},
{
"answer_id": 45323048,
"author": "YvesgereY",
"author_id": 995896,
"author_profile": "https://Stackoverflow.com/users/995896",
"pm_score": 2,
"selected": false,
"text": "std::vector::at(size_type pos)"
},
{
"answer_id": 60823004,
"author": "Gabriel Staples",
"author_id": 4561887,
"author_profile": "https://Stackoverflow.com/users/4561887",
"pm_score": 4,
"selected": false,
"text": "const const const const const const const const const const const const kDaysInAWeek clang-tidy clang-tidy readability-avoid-const-params-in-decls const void f(const string); // Bad: const is top level.\nvoid f(const string&); // Good: const is not top level.\n void f(char * const c_string); // Bad: const is top level. [This makes the _pointer itself_, NOT what it points to, const]\nvoid f(const char * c_string); // Good: const is not top level. [This makes what is being _pointed to_ const]\n readability-const-return-type const const const const const const const const const const const const const clang-tidy const const void f(const std::string); // Bad: const is top level.\nvoid f(const std::string&); // Good: const is not top level.\n\nvoid f(char * const c_string); // Bad: const is top level. [This makes the _pointer itself_, NOT what it points to, const]\nvoid f(const char * c_string); // Good: const is not top level. [This makes what is being _pointed to_ const]\n const // BAD--do not do this:\nconst int foo();\nconst Clazz foo();\nClazz *const foo();\n\n// OK--up to the implementer:\nconst int* foo();\nconst int& foo();\nconst Clazz* foo();\n const"
}
] |
2008/09/22
|
[
"https://Stackoverflow.com/questions/117293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.