text stringlengths 8 267k | meta dict |
|---|---|
Q: How can I capture all exceptions from a wxPython application? I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?
Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).
I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.
A: For logging standard output, you can use a stdout wrapper, such as this one:
from __future__ import with_statement
class OutWrapper(object):
def __init__(self, realOutput, logFileName):
self._realOutput = realOutput
self._logFileName = logFileName
def _log(self, text):
with open(self._logFileName, 'a') as logFile:
logFile.write(text)
def write(self, text):
self._log(text)
self._realOutput.write(text)
You then have to initialize it in your main Python file (the one that runs everything):
import sys
sys.stdout = OutWrapper(sys.stdout, r'c:\temp\log.txt')
As to logging exceptions, the easiest thing to do is to wrap MainLoop method of wx.App in a try..except, then extract the exception information, save it in some way, and then re-raise the exception through raise, e.g.:
try:
app.MainLoop()
except:
exc_info = sys.exc_info()
saveExcInfo(exc_info) # this method you have to write yourself
raise
A: You can use
sys.excepthook
(see Python docs)
and assign some custom object to it, that would catch all exceptions not caught earlier in your code. You can then log any message to any file you wish, together with traceback and do whatever you like with the exception (reraise it, display error message and allow user to continue using your app etc).
As for logging stdout - the best way for me was to write something similar to DzinX's OutWrapper.
If you're at debugging stage, consider flushing your log files after each entry. This harms performance a lot, but if you manage to cause segfault in some underlying C code, your logs won't mislead you.
A: For the exception handling, assuming your log file is opened as log:
import sys
import traceback
def excepthook(type, value, tb):
message = 'Uncaught exception:\n'
message += ''.join(traceback.format_exception(type, value, tb))
log.write(message)
sys.excepthook = excepthook
A: There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk.
A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:
void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent& event) const
{
try
{
wxAppConsole::HandleEvent(handler, func, event);
}
catch (const std::exception& e)
{
wxMessageBox(std2wx(e.what()), _("Unhandled Error"),
wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));
}
}
It's a C++ example, but you can surely translate to Python easily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to convert a DB2 date-time string into an Excel Date I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this:
2002-01-15-00.00.00.000000
2008-01-05-12.36.05.190000
9999-12-31-24.00.00.000000
Is there an easier way to convert this into the Excel date format than decomposing with substrings?
DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2))
thanks for your help!
A: It's not clear if you talk about formula functions or VBA functions.
Formula functions
Don't use the DateValue function, which expects a string; use the Date function, which expects numeric Year, Month, Day:
=DATE(INT(LEFT(A1,4)),INT(MID(A1,6,2)),INT(MID(A1,9,2)))
assuming that the date-as-string is in A1.
VBA functions
Similar calculation as above, just use the DateSerial function instead:
dt= DateSerial(Int(Left$(dt$, 4), Int(Mid$(dt$, 6, 2)), Int(Mid$(dt$, 9, 2)))
A: I'm sure you could cook something up with Regex's if you really cared to. It wouldn't be any 'better' though, probably worse.
If you'll forgive a bit of C# (I havn't touched VB in years, so I don't know the function calls anymore) you could also do:
DB2string = "2002-01-15-00.00.00.000000";
DB2date = DateValue(DB2string.SubString(0, 10).Replace('-', '/'));
But again, you're not really gaining anything. Can you give an example of where your current code would break?
A: in VBA, dateValue() can convert the first part of the string into a date:
? dateValue("2002-01-15")
15/01/2002
So the right way to get it for you will be
? dateValue(left("2002-01-15-00.00.00.000000",10))
This will always give you the right answer as long as DB2 always give you a "YYYY-MM-DD" date. The format of the result (dd/mm/yy, mm-ddd-yyyy, etc) will depend on the local settings of your computer/specific settings of your cell.
If you want to extract the "time" part of your string, there is this timeValue() function that will eventually make the job.
A: If you want to include the time information you have more to do; DateValue discards it.
TimeValue can evaluate the time part down to seconds, so you can add them:
= DateValue(Mid(a, 1, 10)) + TimeValue(Mid(a, 12, 8))
But your sample data presents another problem: it has both time values "00.00.00" and "24.00.00".
The second one gags the TimeValue function, so you will need to code for the special case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Software development process for small teams I might be an exception here but I have never worked on a team with more than three developers and / or five people. Still we could manage to get the job done (somehow).
Is there a software development process which fits this "extreme" scenario? And, if you work as a standalone programmer is there something you can adapt to your daily life to make it more predicatable, coherent, documented and still get the job done?
A: Let the mighty SecretGeeek teach you how to be a standalone programmer. Enjoy :)
intellisense
||
\/
code >>> compile >>>>> run >>>> success >>>> profit ;-)
/\ || ||
^^ \/ \/
^^ errors errors
^^ \\ //
^^ \\ //
^^ google
^^ ||
\\ \/
\<<<<<<< copy N paste
A: TODO driven development
A serious suggestion from SecretGeek.
Set up your development environment or editor to automatically list all lines with TODO tags - Visual Studio does this by default.
Step 1
*
*Write Class or method outlines (ie, 'Public Class ...' or 'Public Sub...' with no code inside.)
*Include rough logic
*Add pseudo code preprended with "TODO:"
*Only write the very trivial code -- anything else just add a TODO
Step 2
*
*Repeat step 1 until the whole application is roughed out
*You've now got a big list of 'TODO' tasks
*Check for completeness (breadth)
*See what can be removed.
*See what can be simplified (eg, two similar todo comments: can they be made identical?
Step 3
*
*Replace TODO's with calls to non-existant classes, methods etc...
(For test driven development, create exhaustive tests for each of these methods/classes)
Step 4
*
*Fix One Compilation error at a time by:
*
*writing shells of classes, methods etc,
*Adding TODO: pseudo code to each of these as you go.
*(Also Add 'HACK: ' comments and explanations where appropriate, if pressed for time)
*Where appropriate, replace TODO's with the trivial code required
Step 5
*
*Repeat Step 4 until there are no compilation errors left.
*If there are TODO's left, then Go back to step 3.
(There's also a lot of prior planning, paper prototyping, customer meetings, discussion, procrastination, database design, coffee-drinking, code-generation for sprocs and crud-sproc calls, import of re-usable DAL's, PAG block usage, go PAG!, back-and-forth debates prior to document sign-off, arguments, late-nights, frustration, chatting with friends, sifting through email, scratching in visio, printing things out and leaving them in a heap, scrounging for staples, catching buses, doing back and neck stretches etc., but that's all been left out for simplicity...)
(MarkJ again) A bit like the pseudo-code programming process from Code Complete. And we all agree everyone should read Code Complete, right?
A: Most of the agile methodologies fit your profile.
The most popular is currently SCRUM. It's designed for productivity in small teams, and it's fans claim that development times are 5-10 times better than the traditional waterfall methodologies.
I recommend the Headfirst Software Development book if you want to get started on some reading
A: I'd recommend the Crystal Clear method
The Seven Properties
*
*Frequent delivery/integration using time-boxed iterations
*Reflect and improve, criticise and fix
*Osmotic (passive) knowledge acquisition and communication through office organisation and open channels
*Personal Safety, safe to be honest, confidence to court criticism
*Stay focused, clear tasks, priorities on work, limit the workload
*Access to expert users, fast, quality feedback
*The usual agile stuff: automated testing, CM, continuous integration
A: The agile methodologies are a good starting point because, imho, they are better suited for small groups.
As for keeping your personal working pace I'd recommend a method based on TODO lists and some tool like Task2Gather. You might want to look at GTD, too.
Things I would never give up even for a team of me:
*
*source version control
*backups
*TODO
*unit testing/TDD
*code documentation
*refactoring/code reviews
A: Development processes are basically created for large teams to avoid possible chaos. If you're trying to do large projects by yourself, you will fail no matter what development process you use, as you'll need large numbers to accomplish what's needed in time.
If you work on small projects, then any Agile method should do. GTD is no method, it's a method wannabe. It's like me patenting my brain process.
A: Not a direct answer to your question, but Steve McConnell has an article named Less is More written more than a decade ago about why small teams are more productive.
A: Continuous Integration is the first thing I always try to get set up on teams I work on as I believe it is the foundation of good development practices i.e. Integrate often, automated build/release, self testing build, easy for anyone to get latest.
Read more about it here:
http://martinfowler.com/articles/continuousIntegration.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Rails named_scopes with joins I'm trying to create a named_scope that uses a join, but although the generated SQL looks right, the result are garbage. For example:
class Clip < ActiveRecord::Base
named_scope :visible, {
:joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id",
:conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "
}
(A Clip is owned by a Series, a Series belongs to a Show, a Show can be visible or invisible).
Clip.all does:
SELECT * FROM `clips`
Clip.visible.all does:
SELECT * FROM `clips` INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id WHERE (shows.visible = 1 AND clips.owner_type = 'Series' )
This looks okay. But the resulting array of Clip models includes a Clip with an ID that's not in the database - it's picked up a show ID instead. Where am I going wrong?
A: This is a bug:
http://rails.lighthouseapp.com/projects/8994/tickets/1077-chaining-scopes-with-duplicate-
joins-causes-alias-problem
A: The problem is that "SELECT *" - the query picks up all the columns from clips, series, and shows, in that order. Each table has an id column, and result in conflicts between the named columns in the results. The last id column pulled back (from shows) overrides the one you want. You should be using a :select option with the :joins, like:
named_scope :visible, {
:select => "episodes.*",
:joins => "INNER JOIN series ON series.id = clips.owner_id INNER JOIN shows on shows.id = series.show_id",
:conditions=>"shows.visible = 1 AND clips.owner_type = 'Series' "
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Restore Eclipse subversion project connection I have a project in subversion, which I'm developing using Eclipse. I did the original checkout from the svn repository from inside Eclipse. All was well for some weeks then for some unknown reason, Eclipse (specifically: subclipse in Ganymede) no longer recognizes my project as being under svn control. The team context-menu only shows the basic "apply patch" / "share this project" menu options. From the shell, I can still update the project using the svn command line tools, so I know that the svn credentials still work. Other projects under subversion in the same copy of Eclipse still work.
I realise that I can delete the local copy and check it out again, but I'd rather understand what has gone wrong - fix the problem, rather than mask the symptoms. Where does Eclipse store its knowledge of which projects are under version control? I looked at the .project file and the .settings directory, but couldn't see any obvious mention of svn nature or anything similar, even in the projects that are still working properly.
A: Just doing Team -> Share Project (per the answer to this question provided by @Paul Whelan) did not work for me. The Share Project wizard acted as though the project was not already in SVN (even though the .svn folder was present for my project).
I ended up resolving the issue by uninstalling the Subversive and JavaHL add-ons (via Help | About Eclipse | Installation Details button | Installed Software tab | Uninstall...), and then reinstalling Subversive. When prompted after restarting Eclipse, I opted to install the SVNKit connector rather than the JavaHL connector.
After having done that, when I once again tried Team -> Share Project..., Eclipse correctly recognized that my project was already present in SVN, and it successfully restored the connection.
A: Addendum: it turns out that my problem manifests when I start Eclipse outside the company vpn, with a project in the workspace that is attached to a svn repository inside the vpn. Fortunately, switching Eclipse svn plugins from subversive to subclipse did solve it.
Ian
A: From eclipse, I closed the project(s) and reopened which resolved the problem. All by SVN links are back for all projects in my workspace.
A: I found an easy way just reimport the project
A: I had the same problem and this forum helped me in finding the right answer.
My earlier project was configured using subclipse.
The new eclipse had subvesive.
Installing subclipse helped me get back the svn options under team!
Hope it helps someone else.
regards
Anshu Prateek
A: If you are using sublipse as your SVN provider I recommend doing the following
Team -> Share project is usually enough to connect the metadata.
(that is, assuming that the .svn files are still there which they seem to be if you can work on the command line).
As to why this would happen I have no idea.
A: Without knowing what platform you're on, I don't know if your problem is similar to mine. However, I have recently (actually on two different platforms!) had issues where an update to Subversive (or perhaps Eclipse itself, not clear) caused the connectors to no longer load. Without the connectors, Subversive cannot connect to a project. But Eclipse isn't going to lock you out of your project over that, it'll just remove the SVN-related functionality.
Look at the Errors view, which is a log of Eclipse's various errors (class-not-found exceptions, etc.) and see if there are any lines that related to the Subversive components. Unfortunately, I can't really recommend a solution-- on my Mac OSX platform it was enough to re-install the Subversive core elements and connectors. On my Linux machine (possibly due to an OS upgrade) I'm having to completely re-install Eclipse, as too much cruft has accumulated for me to be able to fully investigate it.
A: In the Juno release with Subversive, I did:
*
*File/Import brings up the Import popup.
*From there, select General/Existing Projects in to Workspace.
*In the next pane, you select the root directory. Then it will show you all the
subdirectories. They'll all be selected by default.
*Unselect the ones you don't want.
It will then "import" your existing directory, which can be used in-place they are already located inside your workspace directory.
A: Same in my case: .svn dirs were there, but my project didn't support svn actions.
After a bit of poking it turned out that subversive plugin just disappeared after a forced quitting eclipse.
The solution was to (re)install subversive, and now everything is fine again.
Cheers
v.
UPDATE: I have switched eclipse to a new version that just didn't have the plugin installed, which is the reason why I had to install it from scratch.
A: This worked for me:
right click-> TortoiseSVN -> Settings -> Icon Overlay properties,
Selecting Shell as Status Cache. Click Ok, Refresh page.
A: I can reliably reproduce this problem—it happens when checking out certain Maven projects by running "Check out as Maven Project…" not on the folder containing the POM itself but on a parent directory (such as "trunk"). In this case Subclipse checks out the project without any complaints, putting it in a workspace directory with a placeholder name such as maven.1424425443350. Inside this directory it creates a subdirectory with the name of the Maven artifact. This confuses both Subclipse and Subversion: Subclipse, as we've seen, immediately forgets that the project is under version control, and if you invoke svn status from the command line in the maven.1424425443350 directory, it will tell you that the directory is under version control but that all the version-controlled files are missing.
None of the workarounds presented in the other answers will work if this is what caused Subsclipse to forget its SVN connection. Instead, the only solution is to delete the project and check it out again, this time making sure that the checkout is performed on a directory containing a POM rather than some higher-level directory.
A better overall solution would be for Subclipse to refuse to run "Check out as Maven Project…" on directories which don't contain a POM, or else to better handle cases where it tries to do so anyway by searching subdirectories for Maven projects.
A: I was using two SVNKit implementations (1.7.x and 1.8.x) simultaneously with the SVN repository version (1.8.x).
As a result the Team -> Share projects... always requested a commit message. Obviously, SVNKit 1.7.x was used which is not compatible with SVN 1.8.x.
After removing SVNKit 1.7.x eclipse used the only available correct SVNKit version 1.8.x and everything worked as expected.
A: My .svn metadatas folder were deleted.
None of the solutions here worked for me (close/reopen project, delete/reimport, still unlinked)
Following steps worked for me:
*
*BEFORE ALL backup source project PROJECT/ folder to BAK/
*Eclipse > on Project:
*
*Delete project, choose yes for "Delete content too?"
*Team > checkout as fresh project, recursive
*⇾ restores all up-to-date content and the .svn folders
*Close Eclipse
*Copy / override from BAK/ to PROJECT/:
*
*optional, .classpath and .project files ⇾ restores Project (Java) natures, setup, build path, ... if yours was modified compared to server version (I needed to)
*optional, all source files and folders ⇾ restores your latest local changes (I needed to)
*Open Eclipse
*Eclipse > File > Import project
The project is now restored, it builds and is linked to subversion again, with the latest local recent changes kept if any.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "101"
} |
Q: How can I upload files asynchronously with jQuery? I would like to upload a file asynchronously with jQuery.
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
A: This AJAX file upload jQuery plugin uploads the file somehwere, and passes the
response to a callback, nothing else.
*
*It does not depend on specific HTML, just give it a <input type="file">
*It does not require your server to respond in any particular way
*It does not matter how many files you use, or where they are on the page
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
A: Look for Handling the upload process for a file, asynchronously in here:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Sample from the link
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>dnd binary upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function sendFile(file) {
var uri = "/index.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
</div>
</body>
</html>
A: You can use newer Fetch API by JavaScript. Like this:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..) asynchronously.
A: I have been using the below script to upload images which happens to work fine.
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Explanation
I use response div to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
A: You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percent = (e.position/ e.totalSize);
// Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
// Handle file upload complete
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
A: You can upload simply with jQuery .ajax().
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
CSS
.progress { display: none; }
Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
A: Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload from root of your website, this code should work for you:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
Also some further information about XMLHttpReques:
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox,
IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Access Across Domains
For security reasons, modern browsers do not
allow access across domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the
XML files you load must be located on your own server.
For more details, you can continue reading here...
A: For PHP, look for https://developer.hyvor.com/php/image-upload-ajax-php-mysql
HTML
<html>
<head>
<title>Image Upload with AJAX, PHP and MYSQL</title>
</head>
<body>
<form onsubmit="submitForm(event);">
<input type="file" name="image" id="image-selecter" accept="image/*">
<input type="submit" name="submit" value="Upload Image">
</form>
<div id="uploading-text" style="display:none;">Uploading...</div>
<img id="preview">
</body>
</html>
JAVASCRIPT
var previewImage = document.getElementById("preview"),
uploadingText = document.getElementById("uploading-text");
function submitForm(event) {
// prevent default form submission
event.preventDefault();
uploadImage();
}
function uploadImage() {
var imageSelecter = document.getElementById("image-selecter"),
file = imageSelecter.files[0];
if (!file)
return alert("Please select a file");
// clear the previous image
previewImage.removeAttribute("src");
// show uploading text
uploadingText.style.display = "block";
// create form data and append the file
var formData = new FormData();
formData.append("image", file);
// do the ajax part
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var json = JSON.parse(this.responseText);
if (!json || json.status !== true)
return uploadError(json.error);
showImage(json.url);
}
}
ajax.open("POST", "upload.php", true);
ajax.send(formData); // send the form data
}
PHP
<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$database = 'database';
$mysqli = new mysqli($host, $user, $password, $database);
try {
if (empty($_FILES['image'])) {
throw new Exception('Image file is missing');
}
$image = $_FILES['image'];
// check INI error
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
// check if the file exists
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
$maxFileSize = 2 * 10e6; // in bytes
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
// check if uploaded file is an image
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
$mimeType = $imageData['mime'];
// validate mime type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
// nice! it's a valid image
// get file extension (ex: jpg, png) not (.jpg)
$fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
// create random name for your image
$fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
// Create the path starting from DOCUMENT ROOT of your website
$path = '/examples/image-upload/images/' . $fileName;
// file path in the computer - where to save it
$destination = $_SERVER['DOCUMENT_ROOT'] . $path;
if (!move_uploaded_file($image['tmp_name'], $destination))
throw new Exception('Error in moving the uploaded file');
// create the url
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$domain = $protocol . $_SERVER['SERVER_NAME'];
$url = $domain . $path;
$stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');
if (
$stmt &&
$stmt -> bind_param('s', $url) &&
$stmt -> execute()
) {
exit(
json_encode(
array(
'status' => true,
'url' => $url
)
)
);
} else
throw new Exception('Error in saving into the database');
} catch (Exception $e) {
exit(json_encode(
array (
'status' => false,
'error' => $e -> getMessage()
)
));
}
A: The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.
That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
You can also read the contents of the iframe onLoad for server errors or success responses and then output that to user.
Chrome, iFrames, and onLoad
-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading
Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.
The only solution that I found works for Chrome was to use a cookie.
To do that basically when the upload/download is started:
*
*[Client Side] Start an interval to look for the existence of a cookie
*[Server Side] Do whatever you need to with the file data
*[Server Side] Set cookie for client side interval
*[Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.
Using a cookie for this is ugly but it works.
I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
The same basic principal applies to uploading, as well.
To use the downloader ( include the JS, obviously )
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
And on the server side, just before transferring the file data, create the cookie
setcookie('iDownloader', true, time() + 30, "/");
The plugin will see the cookie, and then trigger the onComplete callback.
A: You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -
*
*ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
*ASP.NET MVC based Multiple File Upload made in jQuery
The server side language is C# but you can do some modification for making it work with other language like PHP.
File Upload ASP.NET Core MVC:
In the View create file upload control in html:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
Now create action method in your controller:
[HttpPost]
public async Task<IActionResult> Add(IFormFile[] mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
A: Try
async function saveFile()
{
let formData = new FormData();
formData.append("file", file.files[0]);
await fetch('addFile.do', {method: "POST", body: formData});
alert("Data Uploaded: ");
}
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input type="button" value="Upload" onclick="saveFile()"/>
The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server). Here is more developed example with err handling and json adding
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
A: I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.
The challenge is in getting AJAX upload working as the standard remote_form_for doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.
That's where the jQuery-form plugin comes into play.
Here’s the Rails code for it:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Here’s the associated JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
And here’s the Rails controller action, pretty vanilla:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.
A: Simple Ajax Uploader is another option:
https://github.com/LPology/Simple-Ajax-Uploader
*
*Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
*Supports multiple, concurrent uploads -- even in non-HTML5 browsers
*No flash or external CSS -- just one 5Kb Javascript file
*Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
*Flexible and highly customizable -- use any element as upload button, style your own progress indicators
*No forms required, just provide an element that will serve as upload button
*MIT license -- free to use in commercial project
Example usage:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
A: A solution I found was to have the <form> target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
A: Here's just another solution of how to upload file (without any plugin)
Using simple Javascripts and AJAX (with progress-bar)
HTML part
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS part
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP part
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Here's the EXAMPLE application
A: It is an old question, but still has no answer correct answer, so:
Have you tried jQuery-File-Upload?
Here is an example from the link above that might solve your problem:
$('#fileupload').fileupload({
add: function (e, data) {
var that = this;
$.getJSON('/example/url', function (result) {
data.formData = result; // e.g. {id: 123}
$.blueimp.fileupload.prototype
.options.add.call(that, e, data);
});
}
});
A: You could also consider using something like https://uppy.io.
It does file uploading without navigating away from the page and offers a few bonuses like drag & drop, resuming uploads in case of browser crashes/flaky networks, and importing from e.g. Instagram.
It's open source and does not rely on jQuery/React/Angular/Vue, but can be used with it. Disclaimer: as its creator I'm biased ;)
A: 2019 Update: It still depends on the browsers your demographic uses.
An important thing to understand with the "new" HTML5 file API is that it wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average propensity toward older versions of Windows, you might not have access to it.
As of 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (e.g., this is a B2B tool or something you're delivering for training) that number can skyrocket. In 2016, I dealt with a company using IE8 on over 60% of their machines.
It's 2019 as of this edit, almost 11 years after my initial answer. IE9 and lower are globally around the 1% mark but there are still clusters of higher usage.
The important take-away from this —whatever the feature— is, check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client. caniuse is a useful tool but note where they get their demographics from. They may not align with yours. This is never truer than enterprise environments.
My answer from 2008 follows.
However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.
It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.
If you need multiple file uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.
Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...
A: jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
A: With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the .on('change') event of the file:
$(':file').on('change', function () {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k');
}
// Also see .name, .type
});
Now the $.ajax() submit with the button's click:
$(':button').on('click', function () {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
A: var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);
$.ajax({
url:"page.php",
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(data){ }
});
You can use form data to post all your values including images.
A: What if using promises which ajax and checking if the file is valid and well saved in your backend, so you can use some animation in front while user is navigating thought your page.
You can even make it paralel upload or stacking with recursive approach
A: A modern approach without Jquery is to use the FileList object you get back from <input type="file"> when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.
// The input DOM element // <input type="file">
const inputElement = document.querySelector('input[type=file]');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// You can then post it to your server.
// Fetch can accept an object of type FormData on its body
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
A: To upload file asynchronously with Jquery use below steps:
step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))
URL: https://github.com/blueimp/jQuery-File-Upload
step 2 Add below scripts in the HTML files, which are already added to the project by running above package:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
step 3 Write file upload control as per below code:
<input id="upload" name="upload" type="file" />
step 4 write a js method as uploadFile as below:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
step 5 In ready function call element file upload to initiate the process as per below:
$(document).ready(function()
{
uploadFile($('#upload'));
});
step 6 Write MVC controller and Action as per below:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
A: This is my solution.
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
and the js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Controller
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
[...]
}
A: You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:
<from action="" id="formContent" method="post" enctype="multipart/form-data">
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.
$(document).ready(function () {
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("successfully submitted");
});
});
});
View more details
A: You can use
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Demo
A: I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
A: Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.
Example
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
I hope it would be helpful
A: Note: This answer is outdated, it is now possible to upload files using XHR.
You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.
A: Wrapping up for future readers.
Asynchronous File Upload
With HTML5
You can upload files with jQuery using the $.ajax() method if FormData and the File API are supported (both HTML5 features).
You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".
Fallback
When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.
It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.
If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.
In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax() method like this:
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Plugins
Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.
A: Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder.
Fiddle here
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Then to retrieve:
window.open("data:application/octet-stream;base64," + base64);
A: You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here
A: You can use the following code.
async: false(true)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3119"
} |
Q: Can't merge undo disks on Virtual Server 2005 Error message: "Virtual Server was unable to commit the changes made during the current session of "". A likely cause of this problem is the parent virtual hard disk cannot be opened for read/write or it might be in use or the user has no read/write/modify permissions. The data in the undo disk is retained."
I can start up that virtual machine, do work on it, it gets saved, but when I try to overwrite the undo disk, I get this message. How can I check if I have the required permission to overwrite the undo disk? Of course I turned off the virtual machine first, and tried to initiate a "Merge Undo Disks" operation that way, so I don't think that the virtual hard disk is locked.
UPDATE: the virtual hard disk file could be renamed, so there is nothing locking that file.
A: Once saw this as well.
Here is a solution thanks to Kurt Guenther.
*
*Rename the undo disks to *.vhd. This turns them into a virtual drive in the eyes of Virtual Server.
*Click on the Inspect option in the Virtual Disk section of Virtual Server. There should be an option to then merge the disk.
*Select a new disk to merge into. If you try merging into the original parent, Virtual Server will just give you the above error again.
*Take your newly merged virtual disk and replace it in the virtual machine (i.e. replace the parent that was couldn't be merged to before).
Make sure you have enough diskspace left before you start this procedure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tcl/Tk examples? Tcl/Tk is a simple way to script small GUIs.
Can anyone give a nice example with a button and a text widget. When the button is pressed should a shell command be executed and the output piped to the text widget.
If you have other nice and clean examples for useful tasks, please add them too.
A: Some suggestions:
To append the output to the text widget, instead of specifying line 999999, you can use the index end, which refers to the position just after the last newline. For example,
.main insert end "$x\n"
To have the text scroll as the command is outputting, use the see command. For example, after appending to the .main text widget
.main see end
You may also want to consider grabbing the command output asynchronously, by using the fileevent command.
A: I can give a start...please suggest improvements. I.e I'd like it to scroll as the command is outputting
#!/usr/bin/wish
proc push_button {} {
put_text
.main see end
}
proc put_text {} {
set f [ open "| date" r]
while {[gets $f x] >= 0} {
.main insert end "$x\n"
}
catch {close $f}
}
button .but -text "Push Me" -command "push_button"
text .main -relief sunken -bd 2 -yscrollcommand ".scroll set"
scrollbar .scroll -command ".main yview"
pack .but
pack .main -side left -fill y
pack .scroll -side right -fill y
A: wiki.tcl.tk is good website for all kinds of examples
A: Here's a more complete example using fileevents. This will auto-scroll all the time. For usability purposes you probably only want to auto-scroll if the bottom of the text is visible (ie: if the user hasn't moved the scrollbar) but I'll leave that as an exercise for the reader to keep this already long example from getting any longer.
package require Tk
proc main {} {
if {[lsearch -exact [font names] TkDefaultFont] == -1} {
# older versions of Tk don't define this font, so pick something
# suitable
font create TkDefaultFont -family Helvetica -size 12
}
# in 8.5 we can use {*} but this will work in earlier versions
eval font create TkBoldFont [font actual TkDefaultFont] -weight bold
buildUI
}
proc buildUI {} {
frame .toolbar
scrollbar .vsb -command [list .t yview]
text .t \
-width 80 -height 20 \
-yscrollcommand [list .vsb set] \
-highlightthickness 0
.t tag configure command -font TkBoldFont
.t tag configure error -font TkDefaultFont -foreground firebrick
.t tag configure output -font TkDefaultFont -foreground black
grid .toolbar -sticky nsew
grid .t .vsb -sticky nsew
grid rowconfigure . 1 -weight 1
grid columnconfigure . 0 -weight 1
set i 0
foreach {label command} {
date {date}
uptime {uptime}
ls {ls -l}
} {
button .b$i -text $label -command [list runCommand $command]
pack .b$i -in .toolbar -side left
incr i
}
}
proc output {type text} {
.t configure -state normal
.t insert end $text $type "\n"
.t see end
.t configure -state disabled
}
proc runCommand {cmd} {
output command $cmd
set f [open "| $cmd" r]
fconfigure $f -blocking false
fileevent $f readable [list handleFileEvent $f]
}
proc closePipe {f} {
# turn blocking on so we can catch any errors
fconfigure $f -blocking true
if {[catch {close $f} err]} {
output error $err
}
}
proc handleFileEvent {f} {
set status [catch { gets $f line } result]
if { $status != 0 } {
# unexpected error
output error $result
closePipe $f
} elseif { $result >= 0 } {
# we got some output
output normal $line
} elseif { [eof $f] } {
# End of file
closePipe $f
} elseif { [fblocked $f] } {
# Read blocked, so do nothing
}
}
main
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How to remotely run a DTSX package from bat file? I am trying to remotely run a DTSX package from a bat file with this command:
DTEXEC /DTS "\File System\MY_PACKAGE_NAME" /SERVER MY_SERVER_NAME /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING V
This is working fine locally but failing remotely (I do have admin rights on the machine I am pointing to and I have SQL permissions as well) I am getting a timeout error (Login timeout expired).
A: It's very possible, and so easily. There is no need to have a store procedure, nor SQL agent, or Web, or .NET development. I am surprised the Microsoft never suggested this:
*
*Schedule a task on the SQL Server to run the DTSX package. Disable it, so it won't run until you manually execute it from a remote PC.
*Execute the task from the PC using the command:
schtasks /run /tn MyTask [/s MySQLServer [/u [domain]user /p password]] /?
Note: if you do not like exposing the password, use the 'PSEXEC' command to execute the 'schtasks' command(download the free and powerful tool from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
A: After a bit of research it looks like it is impossible to run DTEXEC remotely (it needs to be run locally - remote execution is not supported).
To overcome this limitation the following method seems to be broadly implemented:
*
*set up a SQL job to run the DTSX package
*set up a Stored Procedure to run the job
*use isql command line in a BAT file (remotely executed) to run the stored procedure on the relevant SQL instance (with SQL credentials and not machine credentials)
A: SSIS also exposes a web service on the hosting server. You could via code, query a machine for packages, run packages via database or file system and add / modify variables of the package programmatically via any programming platform you like.
That being said you could also set up your webservice to call your local batch file which contains your 'DETEXEC' command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I make an array of constants in a NSIS install script? I have a large number of NSIS install scripts (.nsi files) that simply define a bunch of constants and then the main installer logic resides an include file (.nsh) which is common to each of the installers. One of the include files looks like this:
!ifdef ABC_SUBFOLDER
RMDir /r "$ABCPath\Data\${ABC_SUBFOLDER}"
SetOutPath "$ABCPath\Data\${ABC_SUBFOLDER}"
File /r "${LOCAL_FOLDER}\ABC\${ABC_SUBFOLDER}\*.*"
!endif
!ifdef ABC_SUBFOLDER2
RMDir /r "$ABCPath\Data\${ABC_SUBFOLDER2}"
SetOutPath "$ABCPath\Data\${ABC_SUBFOLDER2}"
File /r "${LOCAL_FOLDER2}\ABC\${ABC_SUBFOLDER2}\*.*"
!endif
!ifdef ABC_SUBFOLDER3
RMDir /r "$ABCPath\Data\${ABC_SUBFOLDER3}"
SetOutPath "$ABCPath\Data\${ABC_SUBFOLDER3}"
File /r "${LOCAL_FOLDER3}\ABC\${ABC_SUBFOLDER3}\*.*"
!endif
... and so on up to 15 subfolders that may or may not be defined in the top level .nsi file. My question is, is there any better syntax in NSIS to achieve this without cut and pasting every time I need to increase the number of subfolders to support?
A: You could use ${${VAR}} to access different variables depending on the value of another variable. e.g.
RMDir /r "$ABCPath\Data\${ABC_SUBFOLDER${FOLDERNUMBER}}"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to configure an assembly in Global Assembly Cache? Is there a way to configure an assembly in GAC? I want to add a custom configuration to my assembly with System.Configuration.
Mher
A: If I understand your question right, no, there is no way to do this.
An assembly uses the configuration file of the application that loads it.
A: Depending on what scenario you are trying to achieve, you could include your App.config file as an embedded resource and when required extract to somewhere on disk and load using the advice given to this question.
Obviously this removes the ability to actually change the config without recompiling, so kind of defeats the purpose.
Another option might be to have the config file intalled into either the Application Data or Common Application Data folder, and use the same technique as above.
A: There's no easy way to do this in the standard .NET framework. If you use the Enterprise Library configuration components, the FileConfigurationSource class will allow you to target a configuration file in another location. There's also a sneaky way to use the standard ConfigurationManager's OpenExeConfiguraion method to do it. I wrote a post on my blog called Creating Dummy Targets For Configuration Objects that describes how it's done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle instant client with OraOLE DB provider? Is it possible to use oracle instant client for application that use oraoledb driver for connecting to oracle 9i DB.
A: I don't believe so. The Instant Client FAQ states
What can Instant Client be used for?
Instant Client can be used to run your OCI, OCCI, ProC, JDBC, and ODBC applications without installing a full Oracle Client. In addition, Instant Client supports SQLPlus. As of Instant Client 10.2, it is also possible to develop applications for OCI and OCCI using the Instant Client SDK download.
OLE DB is conspicuously absent from that list. Now, potentially, you could use the Microsoft OLE DB to ODBC provider along with the Instant Client and ODBC, but adding additional layers to software is never very fun.
A: I think it is possible. Look for Oracle Data Access Components (ODAC). I've downloaded the ODAC XCopy version, then:
*
*unzip on some tmp folder
*open cmd as administrator
*run install.bat (I've run: install oledb c:\oracle\odac_12_1 odac true)
Despite being on this script, the command regsvr32 (to register the oraoledb12.dll, in my case) didn't work. But running this command after the script worked. Check the PATH variable as well because the script could only change it for the prompt session.
Now I'm being able to connect to a Oracle DB using OraOLEDB.Oracle provider and Oracle Instant Client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Disabling a EventTrigger\Storyboard Dynamically <Grid.Triggers>
<EventTrigger RoutedEvent="Border.Loaded">
<EventTrigger.Actions >
<BeginStoryboard>
<Storyboard x:Name="MyStoryboard" AutoReverse="True" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="border" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:01" Value="#FFFAFAFA"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>
How do I enable\disable this event trigger\animation dynamically. I was thinking I could bind to a IValueConverter and disable the storyboard, but there does not seem to be any suitable property to bind to?
A: The only trigger currently available in Silverlight is "Loaded", for all other events you'll have to write a bit of code. To use this technique, Storyboards should go in the Resources section instead of Triggers, and you'll call Begin() on the Storyboard from the code.
If you're doing templating of a control, then there are what are called Transitions which let you kick off storyboards based on control events, like MouseOver. This is handled by the Visual State Manager:
http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx
A: I wasn't really looking for the animation to be turned off based on an event. I wanted to do it based on a property of my business object that Im binding too? I was hoping there was something like Storyboard.Enabled = False!?!?!
A: You can't do what you are asking for with triggers in Silverlight. There's not a way to have a conditional in the trigger.
You can wire up the Loaded event, check your condition there, and if it's met start the storyboard. However, there is not a XAML-only equivalent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Differences between JDK and Java SDK Is there any substantial difference between those two terms?. I understand that JDK stands for Java Development Kit that is a subset of SDK (Software Development Kit). But specifying Java SDK, it should mean the same as JDK.
A: Taken from the Java EE 6 SDK Installer, shows what SDK 6 contains besides JDK:
A: Sun just likes changing the names of things for no apparent reason. Look at the three different numbering schemes for SunOS/Solaris, or the two numbering schemes for Java. Is is Java 1.6, Java 2 Version 6, or Java 6?
A: JDK is the SDK for Java.
SDK stands for 'Software Development Kit', a developers tools that enables one to write the code with more more ease, effectiveness and efficiency.
SDKs come for various languages. They provide a lot of APIs (Application Programming Interfaces) that makes the programmer's work easy.
The SDK for Java is called as JDK, the Java Development Kit.
So by saying SDK for Java you are actually referring to the JDK.
Assuming that you are new to Java, there is another term that you'll come across- JRE, the acronym for Java Runtime Environment.
JRE is something that you need when you try to run software programs written in Java.
Java is a platform independent language. The JRE runs the JVM, the Java Virtual Machine, that enables you to run the software on any platform for which the JVM is available.
A: Yes, there is a difference between the SDK and the JDK.
Most of people forget that Java Platform is not only used to develop programs in Java language. The JVM supports some other languages also.
Thus, making it clear, the SDK is the generic bundle of software that supports software creation in a variety of languages like Clojure, Groovy, Scala, JRuby, and others.
The JDK is the specific bundle to develop software in Java language, containing all Java standard API to do so.
(I hope I've explaned it well, since I actually do not speak english)
A: The JDK (Java Development Kit) is an SDK (Software Dev Kit).
It is used to build software/applications on Java
and of course it includes the JRE (Java Runtime Edition) to execute that software.
If you just want to execute a Java application, download only the JRE.
By the way, Java EE (Enterprise Edition) contains libraries of packages of classes "with methods (functions)" to build apps for the WEB environment and Java ME (Micro Edition) for mobile devices. If you are interested in it (Java ME) I would recommend to take a look at Google's Android DevKit and API.
Take a look here: it's gonna explain bit more..
http://www.oracle.com/technetwork/java/archive-139210.html
A: The JDK comes with a collection of tools that are used for developing and running Java programs,
They include:
*
*appletviewer (for viewing Java applets)
*javac (Java compiler)
*java (Java interpreter)
*javap (Java disassembler)
*javah (for C header files)
*javadoc (for creating HTML documents)
*jdb (Java debugger)
Whereas, the SDK comes with many other tools also including the tools available in JDKs.
http://parvindersingh.webs.com/apps/forums/topics/show/8853125-solved-java-difference-between-jdk-and-sdk-
A: There is no difference.
The Java Software Development Kit (Java SDK) used to be called the Java Development Kit (JDK) before the marketing department at Sun got crazy with the "tm" and terminology. For political reasons & for sanity, they call the meaningful names (jdk) & versions (1.2 / 1.3 / 1.4 1.5 / 1.6) "engineering" terms. The marketing terms are "Java2 platform" (aka jdk 1.2 thru 1.4) or Java5 (aka jdk 1.5) or Java6 (aka jdk1.6). I'm getting a headache just thinking about it.
A: Best example for this Question, SDK - Software Development Kit - Ex: Netbeans JDK - Java Development Kit.(This is Java compiler). Without JDK, we unable to run java programs in SDK.
A: From this wikipedia entry:
The JDK is a subset of what is loosely defined as a software development kit (SDK) in the general sense. In the descriptions which accompany their recent releases for Java SE, EE, and ME, Sun acknowledge that under their terminology, the JDK forms the subset of the SDK which is responsible for the writing and running of Java programs. The remainder of the SDK is composed of extra software, such as Application Servers, Debuggers, and Documentation.
The "extra software" seems to be Glassfish, MySQL, and NetBeans. This page gives a comparison of the various packages you can get for the Java EE SDK.
A: There's no difference between JDK and Java SDK. Both of them mean the same thing. I think it was a PR decision at Sun to change over from JDK to Java SDK. I think its back to JDK for now.
A: In my point of view there is no difference between JDK and SDK in java. We can find all development tools as well as facilities in both of them. it is just an alias provided by sun.
A: My initial guess would be that the Java SDK is for building the JVM while the JDK is for building apps for the JVM.
Edit: Although this looks to be incorrect at the moment. Sun are in the process of opensourcing the JVM (perhaps they've even finished, now) so I wouldn't be too surprised if my answer does become correct... But at the moment, the SDK and JDK are the same thing.
A: I think jdk has certain features which can be used along with particular framework. Well call it SDK as a whole.
Like Android or Blackberry both use java along with their framework.
A: *
*The JDK is what you need to write a java program.
*The JRE is what you need to need to run a java program.
*Since the JDK contains the JRE you can download the JDK to write and run java program.
*The JRE contains JVM which makes java program run on any platform as long as the JVM is installed on that OS (without having to rewritten or recompiled the code again for other platform). This is why Java is known to be
Write Once(compile once) run anywhere.(WORA)
A: There are two products JavaSE and JavaEE.
EE is the web application/enterprise edition that allows the development and running of web application.
SE is the plain Java product that has no EE specifics in it, but is a subset of EE.
The SE comes in two types a JDK and a JRE.
There is one big difference that may not be obvious, and I am not sure if it applies to all Operating Systems but under Windows the JRE does not have the server HotSpot JVM, only the client one, the JDK has both, and as far as I know all other OS's have both for the JDK and the JRE.
The real difference is the the JDK contains the Java compiler, that is the JDK allows you to compile and run Java from source code where as the JRE only allows the running of Java byte code, that is Source that has already been compiled.
And yes newer versions bundle a number of extra components, such as NetBeans editor environment and Java in memory Database (derby/cloudscape), but these are optional.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
} |
Q: jQuery slideToggle jumps around I'm using the jQuery slideToggle function on a site to reveal 'more information' about something. When I trigger the slide, the content is gradually revealed, but is located to the right by about 100 pixels until the end of the animation when it suddenly jumps to the correct position. Going the other way, the content jumps right by the same amount just before it starts its 'hide' animation, then is gradually hidden.
Occurs on IE7/8, FF, Chrome.
Any ideas on how I would fix this?
Thanks in advance.
A: This is just a shot in the dark, but if the function is manipulating the height css property of your element(s), according to this site you have to separate the padding and display:none in your css to keep it from jumping
A: Solved by adding to the toggled div:
overflow: hidden; position: relative;
A: I have found a workaround, but I'm still not sure of the details. It seemed that when the 'overflow: hidden' style was added by jQuery, the effect that a nearby floated element had changed. The workaround was to place a permanent 'overflow: hidden' on the slideToggle'd div, and also a negative margin-left to counterbalance the effect.
I am surprised that changing the overflow value has such an effect on layout, but there you have it...
A: Does your document contains any DOCTYPE declaration? Without it, some browser render the page in "quirck" mode which doesn't always lead to the result you are expecting..
see here
To make sure your page render as intended, add the following declaration to the top of the page (that is, before the html tag).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
A: setting the height/width of the component you want to slide fixes a bug that causes "jumpyness" using a line like (reference):
$('#slider').css('height', $('#slider').height() + 'px');
A: I had this exact same problem but only when the hidden element was a <div>. I tried everything on this page but the only thing that worked was using overflow:hidden;.
But the problem with using overflow:hidden; is that the upper & lower spacing created by the paragraph element was suddenly removed thereby making the layout ugly.
I changed my hidden element from a <div> to a <p> and removed the overflow:hidden;... it worked without messing up the layout and the jumping problem did not return.
EDIT:
On a new site I was determined to use a hidden <div> and I discovered some things about this issue...
1) When div contains p or ul or similar the jumping occurs.
2) When the div only contains text, a links and/or images, no jumping animation.
3) Removing all margins & padding from the elements within the hidden div clears up the issue. Other things like line-breaks can be added to compensate for the lack of padding & margins... not ideal but the animation is smooth again.
A: I had the same problem with the .slideToggle, and BenAdler is right. Put everything you want to toggle in a div, and set the style for the div to something that contains overflow:hidden and position: relative. It will work fine after that.
A: Try messing with how the element is positioned/displayed/floated. I've had similar problems which were solved by playing with those settings.
A: I've encountered the same error, solved it by positioning the element with
position: relative; width: 709px;
The fixed width did the trick.
A: you can use a structure like this one:
<div class="details">
<div class="hidden"> [your toggled info] </div>
</div>
and in your css
.details{
position:relative;
}
.hidden{
display:none;
}
i think thats it.
your jquery call must be:
$('.hidden').slideToggle("slow");
A: Just to share a solution that worked for me.
I am using a responsive layout for a site I am working on and essentially using slidetoggle on one of my columns in my layout, the only solution that worked above was setting a fixed width to my content - however as the column widths are dynamic this is not a solution for me.
Wrapping the content I wanted to toggle in an extra <div> and then using slide toggle on the new div seemed to do the trick. Try adding position:relative to original element you were trying to slidetoggle.
Yes, this does add horrible unnecessary markup but it's the only way I could get it to work.
A: Adding CSS3 transition/transform properties always solved any jumping issues for me with slideToggle... Example:
-webkit-transform-origin: top;
-moz-transform-origin: top;
-ms-transform-origin: top;
-o-transform-origin: top;
transform-origin: top;
-webkit-transition: transform 0.26s ease;
-moz-transition: transform 0.26s ease;
-ms-transition: transform 0.26s ease;
-o-transition: transform 0.26s ease;
transition: transform 0.26s ease;
transition: -webkit-transform 0.26s ease;
A: This is an old one but similar problems still exist, below a working solution with a couple more requirements.
http://jsfiddle.net/bfnGu/7/
A: Accidentally I think that the easiest to use solution is to add custom function to jQuery with animate padding/margin-top/bottom too.
//this function is to avoid slideToggle jQuery jump bug.
$.fn.slideShow = function(time,easing) { return $(this).animate({height:'show','margin-top':'show','margin-bottom':'show','padding-top':'show','padding-bottom':'show',opacity:1},time,easing); }
$.fn.slideHide = function(time,easing) {return $(this).animate({height:'hide','margin-top':'hide','margin-bottom':'hide','padding-top':'hide','padding-bottom':'hide',opacity:0},time,easing); }
And useage example:
$(this).slideShow(320,'easeOutQuart');
$(this).slideHide(320,'easeOutQuart');
My example animated opacity toggle tu, you can modify it as you need.
A: The only thing that helped for me: give the content to scroll a width.
A: had the same problem , found a problem maybe someone else had it .
if you have min-height -> than you have a problem with slideToggle
A: I had the same problem, but overflow:hidden and position: relative had no effect. I put margin-bottom: -10px on the element that was toggling in, and it solved the issue.
A: I had this issue when using floated elements inside the element that is toggled. Setting a width of 100% against the toggled element fixed this for me. If you wish to use padding then you may also set the box-sizing to border-box.
Relative positioning is not required but you may wish to use overflow: hidden to clear the floated elements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: .Net Localization problem I am currently building an Excel 2007 Add-in using VSTO (latest version + sp1) and .Net 3.5
The code simply takes the position a chart using the Top and Left properties and stores it in an XML file.
The problem im facing is that when the xml is generated using a Vista Ultimate + Excel 2007 + English environment the code works perfectly. When i move this to a Windows Server 2003 + Excel 2007 + French environment it crashes when I try to set the Top and Left properties. Further more it always returns 4 for both values on the server machine.
I have tried to play with the region and language settings but it has not changed anything so far.
I have also tried to store the values as integers instead of the float values being returned by the VSTO objects.
If someone has sone sort of idea what may be going wrong please point me in the right direction.
I will edit once ive traced some more...
A: I'm not sure if this will help or not, but you may want to check out the System.Xml.XmlConvert class. This class will allow you to serialize data types to a string value that is locale independent. When you extract the xml on another machine you can convert the value back into the appropriate data type using this same class and it will assume the Culture of the current environment.
A: You need to post more info about exactly what you are doing and what error you are seeing. Probably you need to be formatting / parsing the numeric values using CultureInfo.InvariantCulture rather than the default CultureInfo.CurrentCulture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL Query which returns a table where each row represents a date in a given range Is it possible to create a SQL query which will return one column which contains the dates from a given date range (e.g. all dates from last year till today). E.g.
dat
----
2007-10-01
2007-10-02
2007-10-03
2007-10-04
...
I am wondering if this is possible as an alternative to creating a table which holds all those dates precalculated.
Updated: I need a solution for MYSQL. I am not interested in any other DBs in this case.
A: AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.
Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.
DECLARE @start datetime
DECLARE @end datetime
DECLARE @results TABLE
(
val datetime not null
)
set @start = '2008-10-01'
set @end = getdate()
while @start < @end
begin
insert into @results values(@start)
SELECT @start = DATEADD (d, 1, @start)
end
select val from @results
This outputs:
2008-10-01 00:00:00.000
2008-10-02 00:00:00.000
2008-10-03 00:00:00.000
A: Prior to CTEs, one would use a standard pre-loaded table of integer numbers (usually a few thousand in a utility table see this article) and join to it as necessary. This would work for you in mysql:
CREATE TABLE dbo.Numbers
(
Number INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
)
WHILE COALESCE(SCOPE_IDENTITY(), 0) <= 1024
BEGIN
INSERT dbo.Numbers DEFAULT VALUES
END
SELECT DATEADD(dd, Number, DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(yy, -1, GETDATE())))) AS Date
FROM Numbers
WHERE Number BETWEEN 0 AND 366
In SQL Server 2005, you can use common table expressions and recursion:
WITH DateRange(Date) AS
(
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(yy, -1, GETDATE()))) AS Date
UNION ALL
SELECT DATEADD(day, 1, Date) AS Date
FROM DateRange
WHERE Date <= GETDATE()
)
SELECT Date
FROM DateRange
OPTION (MAXRECURSION 366)
A: I do not have a MySQL instance at hand just now, but see if this will do. Substitute parameters as appropriate. I hard-coded 2007-01-01 for the example.
Regards.
SELECT
ADDDATE('2007-01-01' INTERVAL SeqValue DAY) DateValue
FROM
(
SELECT
(HUNDREDS.SeqValue + TENS.SeqValue + ONES.SeqValue) SeqValue
FROM
(
SELECT 0 SeqValue
UNION ALL
SELECT 1 SeqValue
UNION ALL
SELECT 2 SeqValue
UNION ALL
SELECT 3 SeqValue
UNION ALL
SELECT 4 SeqValue
UNION ALL
SELECT 5 SeqValue
UNION ALL
SELECT 6 SeqValue
UNION ALL
SELECT 7 SeqValue
UNION ALL
SELECT 8 SeqValue
UNION ALL
SELECT 9 SeqValue
) ONES
CROSS JOIN
(
SELECT 0 SeqValue
UNION ALL
SELECT 10 SeqValue
UNION ALL
SELECT 20 SeqValue
UNION ALL
SELECT 30 SeqValue
UNION ALL
SELECT 40 SeqValue
UNION ALL
SELECT 50 SeqValue
UNION ALL
SELECT 60 SeqValue
UNION ALL
SELECT 70 SeqValue
UNION ALL
SELECT 80 SeqValue
UNION ALL
SELECT 90 SeqValue
) TENS
CROSS JOIN
(
SELECT 0 SeqValue
UNION ALL
SELECT 100 SeqValue
UNION ALL
SELECT 200 SeqValue
UNION ALL
SELECT 300 SeqValue
UNION ALL
SELECT 400 SeqValue
UNION ALL
SELECT 500 SeqValue
UNION ALL
SELECT 600 SeqValue
UNION ALL
SELECT 700 SeqValue
UNION ALL
SELECT 800 SeqValue
UNION ALL
SELECT 900 SeqValue
) HUNDREDS
) SEQ
WHERE
SEQ.SeqValue < = 366 AND
ADDDATE('2007-01-01' INTERVAL SeqValue DAY) < ADDDATE('2007-01-01' INTERVAL 1 YEAR)
ORDER BY
ADDDATE('2007-01-01' INTERVAL SeqValue DAY) ASC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: obtain current svn revision in webapp what is the best way of displaying/using the revision number in a java webapp?
we just use ant to build our .war archive, no buildserver or such. i'd hope there was some kind if $ref that i could write in a resource file, but this is only updated when the file in question is committed. i need it globally.
what would you recommend? post-commit triggers that update certain files?
custom ant scripts? is there a more non-hacky way of doing this?
or it it better to have my own version number independent of svn.
edit: great suggestions! thanks a lot for the answers!
A: We use the following ant task to include the svn version in a attribute in the jar, along with the version of other packages that are being used
<target name="package" depends="compile" description="Package up the project as a jar">
<!-- Create the subversion version string -->
<exec executable="svnversion" failifexecutionfails="no" outputproperty="version">
<arg value="."/>
<arg value="-n"/>
</exec>
<!-- Create the time stamp -->
<tstamp>
<format property="timeAndDate" pattern="HH:mm d-MMMM-yyyy"/>
</tstamp>
<jar destfile="simfraserv.jar">
<manifest>
<attribute name="Built-By" value="${user.name} on ${time.date}" />
<attribute name="Implementation-Version" value="${svn.version}" />
<attribute name="Implementation-Java" value="${java.vendor} ${java.version}" />
<attribute name="Implementation-Build-OS" value="${os.name} ${os.arch} ${os.version}" />
<attribute name="JVM-Version" value="${common.sourcelevel}+" />
</manifest>
<fileset dir="bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="src">
<include name="**"/>
</fileset>
</jar>
</target>
And then you can access it in your webapp like this
String version = this.getClass().getPackage().getImplementationVersion();
A: If you are using ant you can define this task:
<target name="version">
<exec executable="svn" output="svninfo.xml" failonerror="true">
<arg line="info --xml" />
</exec>
<xmlproperty file="svninfo.xml" collapseattributes="true" />
<echo message="SVN Revision: ${info.entry.commit.revision}"/>
<property name="revision" value="${info.entry.commit.revision}" />
</target>
and you the revision value where you want.
A: There are a couple of Ant tasks that can do this for you.
SvnAnt task from tigris is the oldest.
Documentation is here - in particular take a look at the info element which exposes the Subversion repository's revision number as an Ant property which it calls rev. You can write this value to your resouces file using the normal Ant substituion mechanisms.
Someone has also put up a simillar (simpler) task on google code hosting - never used it though so can't comment.
Either of these seem like the neatest way to me if you already have Ant in your build.
A: See this thread.
My favourite from that thread is just dumping $Id:$ in your code where you want the revision ID. SVN will populate that with the real data when you do an export.
A: If you are using windows you could look at SubWCRev.exe which comes with tortoise.
It gives the current repository revision and will replace $WCREV$ with said, you could include this in your web.xml as say a context param and then get it from there.
A: Before the webapp is packaged, run svn info and redirect the output to some file in WEB-INF/classes. When the webapp starts up, parse this file and have it stashed away in the servlet context or some similar place. In the footer of every page, display this version - if you are using something like Tiles or SiteMesh, this change needs to be done only in one file.
Maven users can try the maven-buildnumber plugin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What is Microsoft's official stance on using WCF with Visual Studio 2005? I noticed last night that the WCF extensions for Visual Studio 2005 aren't available on their site any longer. I've read that they want people to use Visual Studio 2008 for WCF/WF/WPF.
Have they made an official statement regarding this?
edit:
I already have the CTP3 for VS2005. I want to know what Microsoft's official stance is. Yes, I've read the threads and the blogs. If a blog post is all that is needed to make it official then so be it.
A: I faced the same problem... I needed to use WCF from Visual Studio 2005 and when I installed VS2008 the WCF extensions were gone.
I googled around a lot and I found a hack to being able of working with WCF in Visual Studio 2005 or 2008.
You have to run the following command from a VS2005 command promtp: msiexec /i vsextwfx.msi WRC_INSTALLED_OVERRIDE=1
For a little more info take a look at the post I wrote about it here: http://sgomez.blogspot.com/2008/08/visual-studio-2005-extensions-for-wcf.html
A: There was never anything but CTP released for MS Visual Studio 2008
According to this thread MS wants you to move to Visual Studio 2008.
This blog post confirms that.
You could still download the CTP3 for Visual Studio 2005 from a third-party server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parameterized Sql queries This is a nut I'm cracking these days
Application I'm working on has some advanced processing towards SQL. One of the operations selects various metadata on the objects in the current context from different tables, based on the item names in the collection. For this, a range of "select...from...where...in()" is executed, and to prevent malicious SQL code, Sql parameters are used for constructing the contents of the "in()" clause.
However, when the item collection for constructing the "in()" clause is larger than 2100 items, this fails due to the Sql Server limitation of max 2100 Sql parameters per query.
One approach I'm trying out now is creating a #temp table for storing all item names and then joining the table in the original query, instead of using "where in()". This has me scratching my head on how to populate the table with the item names stored in an Array in the .NET code. Surely, there has to be some bulk way to insert everything rather than issuing a separate "insert into" for each item?
Other than that, I'm very much interested in alternative approaches for solving this issue.
Thanks a lot
A: One potential workaround is to use the ability to query XML and simply send all the data for your 'in' as an xml column and then join on that.
The same approach could be used to populate your temp table, but then again, why not just use it directly.
Here's a short sample that should illustrate:
declare @wanted xml
set @wanted = '<ids><id>1</id><id>2</id></ids>'
select *
from (select 1 Id union all select 3) SourceTable
where Id in(select Id.value('.', 'int') from @wanted.nodes('/ids/id') as Foo(Id))
Simply build the xml in your application and pass it as parameter.
A: Hrm, without knowing context and more about the data and how you are using the results and performance issues, i will try to suggest an alternative. Could you possibly split into multiple queries? Do the same as you do now, but instead of building a query with 2100+ in items, build two with 1050 in each, and then merge the results.
A: Prevengint malicious SQL code: > Use a stored procedure.
And yes, SQL Server 2005 has a bulk insert:
http://msdn.microsoft.com/en-us/library/ms188365.aspx
A: You can make use of the SqlBulkCopy class that was introduced with .NET 2.0. It's actually very simple to use. Check it out:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
A: For the bulk update problem: take a look at data adapter with a data table in it. You can set a parameter that allows you to insert/update the items in the table in batches, and you can choose the nr of items in a batch
MSDN article
It seems like you should take a closer look at the business problem or domain to determine a better way to filter items in your query. An IN() clause may not be the best way for you to do this. Maybe adding categories of data or filters instead of a large list of items to include would be better in your case. Without knowing more aout the business problem/context, it's hard to say.
A: Ok, I'm not sure how good this is for you or how performant it is, but here is some code I have used in the past to achieve similar:
CREATE FUNCTION [dbo].[Split](
@list ntext
)
RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
number int NOT NULL)
AS
BEGIN
DECLARE @pos int,
@textpos int,
@chunklen smallint,
@str nvarchar(4000),
@tmpstr nvarchar(4000),
@leftover nvarchar(4000)
SET @textpos = 1
SET @leftover = ''
WHILE @textpos <= datalength(@list) / 2
BEGIN
SET @chunklen = 4000 - datalength(@leftover) / 2
SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))
SET @textpos = @textpos + @chunklen
SET @pos = charindex(',', @tmpstr)
WHILE @pos > 0
BEGIN
SET @str = substring(@tmpstr, 1, @pos - 1)
INSERT @tbl (number) VALUES(convert(int, @str))
SET @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
SET @pos = charindex(',', @tmpstr)
END
SET @leftover = @tmpstr
END
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl (number) VALUES(convert(int, @leftover))
RETURN
END
Then in your other stored procedure, you can pass in a comma delimited string of the IDs, like:
select a.number from split('1,2,3') a inner join myothertable b on a.number = b.ID
Like I say, this is probably really bad because it includes lots of string manipulation, and I can't remember where I got the function from... but it's there for picking at...
I guess that you can also strip out the bits that populate the listpos column if you really don't need to index the original string.
A: SQL Server 2008 will have table parameters. This is the hammer that you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to build and deploy Python web applications I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers?
Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more Python based solution.
I've been looking a bit into zc.buildout, but it's not clear for me what I can/should use it for.
A: Depends on what Your infrastructure is. We're just using debian packages and buildbot to make them.
On other setups, I use Fabric scripts. As for format, I'm just using tbz2 files, but I've heard about people just depoloying eggs.
I'd strongly recommend having proper build and having BuildBot/Hudson to build packages, as using SCM beats the purpose and encourage bad practices.
A: Paver is a rake/make work alike for python. I don't know if this is what your looking for, still haven't found anything equivalent to puppet for python...
A: Would SCons do what you want?
http://www.scons.org/
A: pyinstall looks like it should be a simpler solution for you. At least as far as packaging the python stuff and installing in virtualenv goes. I don't know of a pythonic way to do server configuration...
A: I use Mercurial as my SCM system, and also for deployment too. It's just a matter of cloning the repository from another one, and then a pull/update or a fetch will get it up to date.
I use several instances of the repository - one on the development server, one (or more, depending upon circumstance) on my local machine, one on the production server, and one 'Master' repository that is available to the greater internet (although only by SSH).
The only thing it doesn't do is automatically update the database if it is changed, but with incoming hooks I could probably do this too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: What is an effective way to insert ads into web app? Is AdSense suitable? Since content of web applications is dynamically generated it would appear that AdSense is not going to produce relevant ads.
Is there a way to increase relevancy of the AdSense ads for the web application?
Is it possible to achieve Gmail-like ad functionality at all for third-party applications?
Is there a better ad provider for web apps than Google?
A: Sure it is possible to get relevant AdSense ads on dynamic pages. Only because we call some site "dynamic" (= we generate content on-the-fly), it doesn't mean it is not crawlable by AdSense. It all depends on how URLs on your site are constructed, and how you access pages.
Here's simpified sequence of how AdSense publishes ad on some page :
*
*The user inputs some query/klicks link/whatever is necessary to access dynamic page
*The browser sends the request to server and gets the page with some dynamic content
*AdSense javascript embedded on this page will call AdSense clawler, and request him to visit URL of the page
*The crawler gets this URL, grabs the page, analyzes it to match and display relevant ad (in most cases it has already clawled it before, so it brings proper ad from index).
So to get relevant ad, you must make sure AdSense crawler gets the same URL that user opened, and this URL have to lead to the same content. It is possible as long as you avoid:
*
*pagew with URLs using session IDs, (eg. www.yoursite.com/index.php?pageid=123&sessionid=64875684756)
*pages that change content over time, when using same URL
*pages that need to be logged to, and modify its content to user profile
*pages that use POST to send forms
Check this link from google support to read more about it.
A: There are many niche-specific advertising network available, or channels within larger networks such as TribalFusion. For instance, my company, Lake Quincy Media, specializes in advertising solely for Microsoft Developers. Thus, if you go to an article on one of our sites that is about inheritance, you won't find the usual Google ads suggesting that you update your will and find a good lawyer to discuss ways to transfer your wealth to your heirs. You'll find ads for tools like Resharper and Visual Studio, or perhaps some components or a technical job ad. The key here is that the entire pool of ads available to the site has been narrowly targeted to the specific niche that the web site serves. This allows for targeted ads without the need to index the content and try and use keywords to "guess" at what might be targeted.
A: No, it's not really suitable. As you know, AdSense is based on page content and that's rarely going to target the correct ads unless your site is very focused on one advertising niche.
If you run a huge web-app that gets many millions of pageviews, then you might be able to get something worked out with Google privately. Otherwise, you're left to see what the best of the rest has to offer.
Chitika does have the power to let you specify what niches you want to display adverts from... But their rates and even their quality of adverts aren't up there with Googles. Have a look around. There are thousands of advertising providers and I'm sure you'll find one that fits your model.
... But it's not Google at the moment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Recommendations on a free library to be used for zipping files I need to zip and password-protect a file. Is there a good (free) library for this?
This needs to be opened by a third party, so the password protection needs to work with standard tools.
A: You can try Zip4j, a pure java library to handle zip file. It supports encryption/ decryption of PKWare and AES encryption methods.
Key features:
*
*Create, Add, Extract, Update, Remove files from a Zip file
*Read/Write password protected Zip files
*Supports AES 128/256 Encryption
*Supports Standard Zip Encryption
*Supports Zip64 format
*Supports Store (No Compression) and Deflate compression method
*Create or extract files from Split Zip files (Ex: z01, z02,...zip)
*Supports Unicode file names
*Progress Monitor
License:
*
*Zip4j is released under Apache License, Version 2.0.
A: 7-Zip has the option to add a password in its command-line mode. Perhaps you can exec it to get this result (and it has a good compression ration too).
Drawbacks: external process, hard to make portable (even if 7-Zip is portable itself), not sure of distribution license.
Note that InfoZip's Zip utility, highly portable too, also supports password.
A: UPDATE 2020: There are other choices now, notably Zip4J.
After much searching, I've found three approaches:
A freely available set of source code, suitable for a single file zip. However, there is no license. Usage is AesZipOutputStream.zipAndEcrypt(...).
http://merkert.de/de/info/zipaes/src.zip
(https://forums.oracle.com/forums/thread.jspa?threadID=1526137)
UPDATE: This code is now Apache licensed and released at https://github.com/mobsandgeeks/winzipaes (exported from original home at Google code) . It worked for me (one file in the zip), and fills a hole in Java's opens source libraries nicely.
A commercial product ($500 at the time of writing). I can't verify if this works, as their trial license approach is complex. Its also a ported .NET app:
http://www.nsoftware.com/ipworks/zip/default.aspx
A commercial product ($290 at the time of writing). Suitable only for Wnidows as it uses a dll:
http://www.example-code.com/java/zip.asp
A: You can also try TrueZip. See the following links for features:
https://christian-schlichtherle.bitbucket.io/truezip/
The successor of TrueZip can be found here:
https://christian-schlichtherle.bitbucket.io/truevfs/
A: Here's an example using winzipaes 1.0.1.
Note this is just a gist, I have not tested this code in exactly this form.
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;
File aNewZipFile = new File("/tmp/foo.zip");
File existingUnzippedFile = new File("/tmp/src.txt");
// We use the bouncy castle encrypter, as opposed to the JCA encrypter
AESEncrypterBC encrypter = new AESEncrypterBC();
encrypter.init("my-password", 0); // The 0 is keySize, it is ignored for AESEncrypterBC
AesZipFileEncrypter zipEncrypter = new AesZipFileEncrypter(aNewZipFile, encrypter);
zipEncrypter.add(existingUnzippedFile, "src.txt", "my-password");
// remember to close the zipEncrypter
zipEncrypter.close();
You can them unzip "/tmp/foo.zip" using Winzip (v9+) or 7za (i.e. 7zip) on a Mac, using password "my-password".
Note: it's not clear to me why it is necessary to specify the password twice in the code above. I do not know what would happen if you used different passwords in these two places.
A: This isn't an answer, but it is a caution to keep in mind when evaluating potential solutions.
One very important thing about zip encryption:
There are several types of zip encryption. The old type (part of the original zip standard) is not at all worth bothering with (it can be cracked in less than 10 minutes with apps easily available online).
If you are doing any sort of encryption of zip files, please, please be sure you use one of the strong encryption standards (I believe that WinZip's 128- and 256-bit AES standard is the best supported). Here are the technical specs - we used this when developing our own Java encrypted zip system (can't provide source - sorry - it's internal use only)
The only thing worse than having no encryption is thinking that you have encryption and being wrong :-)
A: If you give a better usage scenario then there are other alternatives.
*
*Do you require the zip to be opened by the standard Zip tools that can handle a zip password?
*The same question as previous are you going to pass this zip to an external entity that has to open the zip?
*Is it internal only and you just want to protect the contents of the zip?
For 3 then you can just use java to encrypt the stream contents of the zip as a normal file, probably best to change the file extension to .ezip or somesuch too.
For 1 and 2 then you can use the chillkat solution as mentioned, or an equivalent.
However be aware that chillkat is not a pure Java solution, it uses JNI.
A: Additional info: I googled a bit more and indeed, it is a quite common question, and it appears there is no free solution (yet?).
Now, the standard algorithm of Zip encryption is well defined: See PKWARE's Application Note on the .ZIP file format. It appears to be an encryption done on the encrypted stream. If somebody feels like coding it...
Now, I wonder why Sun didn't include it in its library? Lack of standard? Patent/legal issue? Too weak to be usable?
A:
Is there a good (free) library for this?
java.util.zip will do the zipping, but it won't do the passwords. And no, I don't know of any free ones that will. The cheapest I've seen is $150 for a developer seat.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "75"
} |
Q: How do I use Ruby for shell scripting? I have some simple shell scripting tasks that I want to do
For example: Selecting a file in the working directory from a list of the files matching some regular expression.
I know that I can do this sort of thing using standard bash and grep but I would be nice to be able to hack quick scripts that will work in windows and linux without me having to memorize a heap of command line programs and flags etc.
I tried to get this going but ended up getting confused about where I should be getting information such as a reference to the current directory
So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?
A: When you want to write more complex ruby scripts, these tools may help:
For example:
*
*thor(a scripting framework)
*gli(git like interface)
*methadone(for creating simple tools)
They give you a quick start to write your own scripts, especially 'command line app'.
A: Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.
So, if you had a script called my_shell_script:
#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
puts value
end
...make it executable (as others have mentioned):
chmod u+x my_shell_script
And call it like so:
> ./my_shell_script one two three four five
You'd get this:
I was passed:
one
two
three
four
five
The arguments work nicely with filename expansion:
./my_shell_script *
I was passed:
a_file_in_the_current_directory
another_file
my_shell_script
the_last_file
Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.
A: "How do I write ruby" is a little beyond the scope of SO.
But to turn these ruby scripts into executable scripts, put this as the first line of your ruby script:
#!/path/to/ruby
Then make the file executable:
chmod a+x myscript.rb
and away you go.
A: The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.
Some helper function can be used for testing execution result
#!/usr/bin/env ruby
module ShellHelper
def test(command)
`#{command} 2> /dev/null`
$?.success?
end
def execute(command, raise_on_error = true)
result = `#{command}`
raise "execute command failed\n" if (not $?.success?) and raise_on_error
return $?.success?
end
def print_exit(message)
print "#{message}\n"
exit
end
module_function :execute, :print_exit, :test
end
With helper, the ruby script could be bash alike:
#!/usr/bin/env ruby
require './shell_helper'
include ShellHelper
print_exit "config already exists" if test "ls config"
things.each do |thing|
next if not test "ls #{thing}/config"
execute "cp -fr #{thing}/config_template config/#{thing}"
end
A: Place this at the beginning of your script.rb
#!/usr/bin/env ruby
Then mark it as executable:
chmod +x script.rb
A: There's a lot of good advice here, so I wanted to add a tiny bit more.
*
*Backticks (or back-ticks) let you do some scripting stuff a lot easier. Consider
puts `find . | grep -i lib`
*If you run into problems with getting the output of backticks, the stuff is going to standard err instead of standard out. Use this advice
out = `git status 2>&1`
*Backticks do string interpolation:
blah = 'lib'
`touch #{blah}`
*You can pipe inside Ruby, too. It's a link to my blog, but it links back here so it's okay :) There are probably more advanced things out there on this topic.
*As other people noted, if you want to get serious there is Rush: not just as a shell replacement (which is a bit too zany for me) but also as a library for your use in shell scripts and programs.
On Mac, Use Applescript inside Ruby for more power. Here's my shell_here script:
#!/usr/bin/env ruby
`env | pbcopy`
cmd = %Q@tell app "Terminal" to do script "$(paste_env)"@
puts cmd
`osascript -e "${cmd}"`
A: In ruby, the constant __FILE__ will always give you the path of the script you're running.
On Linux, /usr/bin/env is your friend:
#! /usr/bin/env ruby
# Extension of this script does not matter as long
# as it is executable (chmod +x)
puts File.expand_path(__FILE__)
On Windows it depends whether or not .rb files are associated with ruby.
If they are:
# This script filename must end with .rb
puts File.expand_path(__FILE__)
If they are not, you have to explicitly invoke ruby on them, I use a intermediate .cmd file:
my_script.cmd:
@ruby %~dp0\my_script.rb
my_script.rb:
puts File.expand_path(__FILE__)
A: The answer by webmat is perfect. I just want to point you to a addition. If you have to deal a lot with command line parameters for your scripts, you should use optparse. It is simple and helps you tremendously.
A: Go get yourself a copy of Everyday Scripting with Ruby. It has plenty of useful tips on how to do the types of things your are wanting to do.
A: By default, you already have access to Dir and File, which are pretty useful by themselves.
Dir['*.rb'] #basic globs
Dir['**/*.rb'] #** == any depth of directory, including current dir.
#=> array of relative names
File.expand_path('~/file.txt') #=> "/User/mat/file.txt"
File.dirname('dir/file.txt') #=> 'dir'
File.basename('dir/file.txt') #=> 'file.txt'
File.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'
__FILE__ #=> the name of the current file
Also useful from the stdlib is FileUtils
require 'fileutils' #I know, no underscore is not ruby-like
include FileUtils
# Gives you access (without prepending by 'FileUtils.') to
cd(dir, options)
cd(dir, options) {|dir| .... }
pwd()
mkdir(dir, options)
mkdir(list, options)
mkdir_p(dir, options)
mkdir_p(list, options)
rmdir(dir, options)
rmdir(list, options)
ln(old, new, options)
ln(list, destdir, options)
ln_s(old, new, options)
ln_s(list, destdir, options)
ln_sf(src, dest, options)
cp(src, dest, options)
cp(list, dir, options)
cp_r(src, dest, options)
cp_r(list, dir, options)
mv(src, dest, options)
mv(list, dir, options)
rm(list, options)
rm_r(list, options)
rm_rf(list, options)
install(src, dest, mode = <src's>, options)
chmod(mode, list, options)
chmod_R(mode, list, options)
chown(user, group, list, options)
chown_R(user, group, list, options)
touch(list, options)
Which is pretty nice
A: let's say you write your script.rb script. put:
#!/usr/bin/env ruby
as the first line and do a chmod +x script.rb
A: This might also be helpful: http://rush.heroku.com/
I haven't used it much, but looks pretty cool
From the site:
rush is a replacement for the unix shell (bash, zsh, etc) which uses pure Ruby syntax. Grep through files, find and kill processes, copy files - everything you do in the shell, now in Ruby
A: As the others have said already, your first line should be
#!/usr/bin/env ruby
And you also have to make it executable: (in the shell)
chmod +x test.rb
Then follows the ruby code. If you open a file
File.open("file", "r") do |io|
# do something with io
end
the file is opened in the current directory you'd get with pwd in the shell.
The path to your script is also simple to get. With $0 you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:
#!/usr/bin/env ruby
require 'pathname'
p Pathname.new($0).realpath()
For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "170"
} |
Q: Experiences using software load balancing vs. a hardware load balancer? The ASP.NET application that I am currently responsible for at my day job has hit its limit in terms of its ability to scale inside a single server. Obviously we are working toward moving session out of process and the test and hopefully deploy date draws near. I would like to draw on the experiencies of people using the built in load balancing in Windows vs. an appliance solution such as one by Baracudda, Coyote Point, F5 etc. Did you start with one and move to the other and why ?
thoughts and advice appreciated in advance...
A: some thoughts
*
*WLBS is often "good enough" to get you started with NLB. However like any great engineer - you need to "measure to know"
*its not just about scale-up its about soft or hard redundancy too. We often NLB between VMs just to give us soft redundancy.
*NLB applies just as much to back-edge as well as front-edge networks
*stepping up to hardware acceleration brings you a new degree of ops costs. New training specialized support, escalation etc.
*look for hardware acceleration to give you a lot more than NLB e.g. DDoS protection, SSL, Compression, Caching, Content Switching, Connection Aggregation, Buffering.
*educate both Devs & Ops SE's about hardware acceleration benefits,a great design can merge the line between network operations and application development.
*hardware buffering on it's own made our ASP.NET around 30% quicker just by reducing our GC time.
*content switching can enable you to transparently merge or migrate disparate systems. We merged MSDN & MSDN2 platforms into a single url space using this technique.
*session stickyness is a dual edged sword - use sparingly - again no substitute for good engineering - measure and test everything
We use both WLBS and NLB within our network - cost often drives the conversation. Treat both as tools in the toolbox, learn their nuances, cost models etc.
A: I have some experience with load balanced solutions, however it really depends how your network and software are designed as to which is the best solution for you to go for.
In terms of solutions I've encountered:
Built in load balancing in windows works well for most cases, although you need to ensure your applications can handle sessions correctly if they're not sticky. etc.
I've used F5 products, mainly as a caching solution, however they were overly complex for us.
We are currently moving off them, as developers were not using them correctly as they were too complex. (Please note these were quite old F5 products.)
We're currently trialing hardware load balancers from Foundry, and we'll probably go with them as they will fit in well with our network architecture. (Which is quite complex.).
So I'd say, if you want a simple solution use load balancing in windows (If your applications will work correctly.).
If not use something more complex.
Regardless of which load balancer you go with, you're making your architecture more complex. So plan and test it carefully.
A: setup a apache mod_proxy cluster.
http://www.howtoforge.com/high_availability_loadbalanced_apache_cluster
easier then you think, and at a fraction of the price
A: F5 comes with SSL Acceleration Chip.
SSL Encryption & Decryption (it's very CPU intensive) using the application servers makes them slow down the processing of actual requests.
In general SSL traffic is terminated at F5 and normal http traffic is sent to application servers. This is called SSL Offloading at the load balancer.
Sinces F5 does this SSL Encryption & Decryption using a chip(Hardware) it is 30 to 40 times faster than the normal encryption & decryption times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Calculate Throughput I have a the following scenarios. I am trying to calculate throughput of the java's XSLT transformer. I have 10 threrads, each iterates 1000 times. The task of the thread is to read the XML and XSLT file and trasnform it and write to a new file.
I want to calculate the TPS. Can you please suggest the way to calculate TPS?
Thanks and Regards,
Srinivas.
A: Well, you want to start a timer at the beginning and stop it when all threads complete. That gives you elapsed time = end time - begin time. Transactions = 10 threads * 1000 iterations = 10000. TPS = 10000 / elapsed time.
The easiest way to do this kind of timing is with a CyclicBarrier. Here's a good writeup of using a barrier action with a CyclicBarrier as a timer (see last example):
*
*http://tech.puredanger.com/2007/11/11/thread-coord/
My final caveat would be that benchmarking something like this is fraught with peril. Some suggestions:
*
*Run more than 1000 iterations. You need to let hotspot warm up. Preferably you should let the test run at least 10 minutes.
*Don't discount GC times. You need to be aware of what GC you're using and how its pause times are affecting your results. Running with -verbose:gc at least a few times is extremely valuable. See here for more: http://java.sun.com/developer/technicalArticles/Programming/GCPortal/
*Run multiple repetitions in the same process until you see repeatable results.
*Do many runs until you believe the numbers are consistent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What are some best practices for OpenGL coding (esp. w.r.t. object orientation)? This semester, I took a course in computer graphics at my University. At the moment, we're starting to get into some of the more advanced stuff like heightmaps, averaging normals, tesselation etc.
I come from an object-oriented background, so I'm trying to put everything we do into reusable classes. I've had good success creating a camera class, since it depends mostly on the one call to gluLookAt(), which is pretty much independent of the rest of the OpenGL state machine.
However, I'm having some trouble with other aspects. Using objects to represent primitives hasn't really been a success for me. This is because the actual render calls depend on so many external things, like the currently bound texture etc. If you suddenly want to change from a surface normal to a vertex normal for a particular class it causes a severe headache.
I'm starting to wonder whether OO principles are applicable in OpenGL coding. At the very least, I think that I should make my classes less granular.
What is the stack overflow community's views on this? What are your best practices for OpenGL coding?
A: The most practical approach seems to be to ignore most of OpenGL functionality that is not directly applicable (or is slow, or not hardware accelerated, or is a no longer a good match for the hardware).
OOP or not, to render some scene those are various types and entities that you usually have:
Geometry (meshes). Most often this is an array of vertices and array of indices (i.e. three indices per triangle, aka "triangle list"). A vertex can be in some arbitrary format (e.g. only a float3 position; a float3 position + float3 normal; a float3 position + float3 normal + float2 texcoord; and so on and so on). So to define a piece of geometry you need:
*
*define it's vertex format (could be a bitmask, an enum from a list of formats; ...),
*have array of vertices, with their components interleaved ("interleaved arrays")
*have array of triangles.
If you're in OOP land, you could call this class a Mesh.
Materials - things that define how some piece of geometry is rendered. In a simplest case, this could be a color of the object, for example. Or whether lighting should be applied. Or whether the object should be alpha-blended. Or a texture (or a list of textures) to use. Or a vertex/fragment shader to use. And so on, the possibilities are endless. Start by putting things that you need into materials. In OOP land that class could be called (surprise!) a Material.
Scene - you have pieces of geometry, a collection of materials, time to define what is in the scene. In a simple case, each object in the scene could be defined by:
- What geometry it uses (pointer to Mesh),
- How it should be rendered (pointer to Material),
- Where it is located. This could be a 4x4 transformation matrix, or a 4x3 transformation matrix, or a vector (position), quaternion (orientation) and another vector (scale). Let's call this a Node in OOP land.
Camera. Well, a camera is nothing more than "where it is placed" (again, a 4x4 or 4x3 matrix, or a position and orientation), plus some projection parameters (field of view, aspect ratio, ...).
So basically that's it! You have a scene which is a bunch of Nodes which reference Meshes and Materials, and you have a Camera that defines where a viewer is.
Now, where to put actual OpenGL calls is a design question only. I'd say, don't put OpenGL calls into Node or Mesh or Material classes. Instead, make something like OpenGLRenderer that can traverse the scene and issue all calls. Or, even better, make something that traverses the scene independent of OpenGL, and put lower level calls into OpenGL dependent class.
So yes, all of the above is pretty much platform independent. Going this way, you'll find that glRotate, glTranslate, gluLookAt and friends are quite useless. You have all the matrices already, just pass them to OpenGL. This is how most of real actual code in real games/applications work anyway.
Of course the above can be complicated by more complex requirements. Particularly, Materials can be quite complex. Meshes usually need to support lots of different vertex formats (e.g. packed normals for efficiency). Scene Nodes might need to be organized in a hierarchy (this one can be easy - just add parent/children pointers to the node). Skinned meshes and animations in general add complexity. And so on.
But the main idea is simple: there is Geometry, there are Materials, there are objects in the scene. Then some small piece of code is able to render them.
In OpenGL case, setting up meshes would most likely create/activate/modify VBO objects. Before any node is rendered, matrices would need to be set. And setting up Material would touch most of remaining OpenGL state (blending, texturing, lighting, combiners, shaders, ...).
A: Object transformations
Avoid depending on OpenGL to do your transformations. Often, tutorials teach you how to play with the transformation matrix stack. I would not recommend using this approach since you may need some matrix later that will only be accessible through this stack, and using it is very long since the GPU bus is designed to be fast from CPU to GPU but not the other way.
Master object
A 3D scene is often thought as a tree of objects in order to know object dependencies. There is a debate about what should be at the root of this tree, a list of object or a master object.
I advice using a master object. While it does not have a graphical representation, it will be simpler because you will be able to use recursion more effectively.
Decouple scene manager and renderer
I disagree with @ejac that you should have a method on each object doing OpenGL calls. Having a separate Renderer class browsing your scene and doing all the OpenGL calls will help you decouple your scene logic and OpenGL code.
This is adds some design difficulty but will give you more flexibility if you ever have to change from OpenGL to DirectX or anything else API related.
A: A standard technique is to insulate the objects' effect on the render state from each other by doing all changes from some default OpenGL state within a glPushAttrib/glPopAttrib scope. In C++ define a class with constructor containing
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
and destructor containing
glPopClientAttrib();
glPopAttrib();
and use the class RAII-style to wrap any code which messes with the OpenGL state.
Provided you follow the pattern, each object's render method gets a "clean slate" and doesn't need to worry about prodding every possibly modified bit of openGL state to be what it needs.
As an optimisation, typically you'd set the OpenGL state once at app startup into some state which is as close as possible to what everything wants; this minimisies the number of calls which need to be made within the pushed scopes.
The bad news is these aren't cheap calls. I've never really investigated how many per second you can get away with; certainly enough to be useful in complex scenes. The main thing is to try and make the most of states once you've set them. If you've got an army of orcs to render, with different shaders, textures etc for armour and skin, don't iterate over all the orcs rendering armour/skin/armour/skin/...; make sure you set up the state for the armour once and render all the orcs' armour, then setup to render all the skin.
A: if you do want to roll your own the above answers work well enough. A lot of the principles that are mentioned are implemented in most of the open source graphics engines. Scenegraphs are one method to move away from the direct mode opengl drawing.
OpenScenegraph is one Open Source app that gives you a large (maybe too large) library of tools for doing OO 3D graphics, there are a lot of other out there.
A: I usually have a drawOpenGl() function, per class that can be rendered, that contains it's opengl calls. That function gets called from the renderloop. The class holds all info needed for its opengl function calls, eg. about position and orientation so it can do its own transformation.
When objects are dependent on eachother, eg. they make a part of a bigger object, then compose those classes in a other class that represents that object. Which has its own drawOpenGL() function that calls all the drawOpenGL() functions of its children, so you can have surrounding position/orientation calls using push- and popmatrix.
It has been some time, but i guess something similar is possible with textures.
If you want to switch between surface normals or vertex normals, then let the object remember if its one or the other and have 2 private functions for each occasion that drawOpenGL() calls when needed. There are certainly other more elegant solutions (eg. using the strategy design pattern or something), but this one could work as far as I understand your problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
} |
Q: Writing a generic class to handle built-in types Not too practical maybe, but still interesting.
Having some abstract question on matrix multiplication I have quickly implemented a matrix for ints, then tested my assumptions.
And here I noticed that just int matrix is not good, if I occasionally want to use it with decimal or double. Of course, I could try just to cast all to double, but that's not convenient way.
Continue with assumption we could have a bunch of objects we are able to add and multiply - why don't use them in my matrix?
So, just after considering it would be a Matrix class now I faced that generic T could not be used, I need it to support some interface which could add and multiply.
And the problem is I could override operators in my class, but I could not introduce an interface which would support operators. And I have an operators in built-in types, but still no interface over them.
What would you do in such a case considering you do not want to duplicate worker class body? Wrappers and implicit casting didn't help me much, I'm interested in a beautiful solution.
Thanks.
A: For this you need generic maths. Luckily I have done this. Usage would be similar to this "complex" (i.e. x+iy) example.
The Operator class is now part of MiscUtil.
A: Well, there is a less tech-heavy way to do just that. You cannot add a new interface for "int" or "double". But you can declare an interface for an object that can multiply and add values of some generic type. And then you can implement the interface for all the types you need:
public interface ICalculator<T>
{
T Add(T x, T y);
T Multiply(T x, T y);
}
public class MatrixMultiplier<T>
{
public MatrixMultiplier(ICalculator<T> calculator) { ... }
}
public class IntCalculator : ICalculator<int>
{
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can you control whether a variable's type is dynamic or static in VB9? I would like to use VB9 but am not sure what syntax to use to say that I want a variable to be statically typed as in C#'s:
var foo = new Whatever();
In previous versions of VB:
Dim foo = New Whatever()
created a dynamically typed variable.
Is there a way to get static typing without actually writing the type in VB9?
A: Yes, you can control this behaviour through the Option directives at the beginning of each file or in the project settings:
Option Strict Off
' The following is dynamically typed: '
Dim x = "Hello"
Option Strict On
Option Infer On
' This is statically typed: '
Dim x = "Hello"
It's best-practice to set Option Strict On as the default for all your projects (can be done in the options dialog). This guarantees the same typing behaviour as in C#. Then, if you need dynamic typing, you can disable the setting selectively on a per-file basis by using the directive mentioned above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Django, mod_python, apache and wacky sessions I am running a Django through mod_python on Apache on a linux box. I have a custom authentication backend, and middleware that requires authentication for all pages, except static content.
My problem is that after I log in, I will still randomly get the log in screen now and again. It seems to me that each apache process has it's own python process, which in turn has it's own internals. So as long as I get served by the same process I logged in to, everything is fine and dandy. But if my request gets served by a different apache process, I am no longer authenticated.
I have checked the HTTP headers I send with FireBug, and they are the same each time, ie. same cookie.
Is this a known issue and are there workarounds/fixes?
Edit: I have a page that displays a lot of generated images. Some off these will not display. This is because they are too behind the authenticating middleware, so they will randomly put up a login image. However, refreshing this page enough times, and it will eventually work, meaning all processes recognize my session.
A: You are correct about how Apache handles the processes, and sometimes you'll get served by a different process. You can see this when you make a change to your site; new processes will pick up the change, but old processes will give you the old site. To get consistency, you have to restart Apache.
Assuming a restart doesn't fix the problem, I would guess it's something in the "custom authentication backend" storing part of the authentication in memory (which won't work very well for a web server). I would try setting MaxRequestsPerChild to 1 in your Apache config and seeing if you still get the login screen. If you do, something is being stored in memory, maybe a model not being saved?
Hope that helps!
P.S. Just out of curiosity, why are you using a custom authentication backend and a middleware to ensure the user is logged in? It seems Django's contrib.auth and @login_required would be easier...
A: Do you have standard database-driven sessions? Is caching enabled in settings?
A: I highly recommend you don't set MaxRequestsPerChild to 1, as that would cause so much overhead as each process gets killed off and respawns with every request.
Are you using apaches preform MPM or worker MPM?
Take a look at http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs that may give you some help
A: If you are using some global variables to hold data of your custom authentication session, you need to change this to use either file, database or memcached. As stated above mod_python launches few processes and there's no shared memory between them.
I recommend using memcached for this, also use cookies to store session ID or pass it with as GET parameter so that later you can easily extract session data from the cache.
A: How to ensure that session is not cleared after Apache restart( or stop and start) ?
Because when I upgrade my source code and restart Apache, I refresh the web page and there I have to login again. Session is lost.
Session is stored in Memcache. No idea how and why its cleared. How to preserve the session so that the user need not login after the apache restart?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What deployment directories do you use for Rails applications (deploying to a debian box)? I wonder what's the best deployment directory for Rails apps? Some developers use directories such as /u/apps/#{appname}. Are there any advantages when using /u/apps/#{appname} instead of /var/www/#{appname} or other OS default directories?
Obviously I want to pick the directory with the best security properties and the least friction for setting up the server environment.
How do you deploy your Rails apps? Why are you using a specific directory? Do you think it really matters anyway?
A: As other people have said, it really doesn't matter where you keep your applications - the thing that does matter is that you're consistent about it, so that whichever server you're on, its just a case of going to the usual location.
I think the only reason people use /u/apps/#{appname} is that it's Capistrano's default setting - certainly it seems odd to me doing things that way.
A: FHS standard would suggest /srv/www/#{appname}.
A: I tend to create a dedicated user for each rails app I run and install, and add that user to the www-data group. So, I tend to have /home/mephisto/www, /home/warehouse/www and so on.
I do this purely for organization, and I don't think it matters much.
A: I use Ubuntu and deploy under /var/rails/appname (underneath that are /releases and /current from Capistrano).
I do this to have a little separation between app types: rails, php, static, ...
I don't think it really matters, as long as you set permissions and ownership properly.
A: Like the other posters I think you should just put them wherever feels most natural. Read man hier if you'd like to see what directories in the standard UNIX hierarchy are meant for. I like putting things somewhere logical under /var
Another very important consideration is that you should never put your Rails application directory somewhere where RAILS_ROOT will be accessible on the web. So sticking an entire Rails application in the subdirectory of a regular site is a big no-no.
A: The CPanel based shared hosting account I use seems to favour /home/etc/rails_apps/...
I think it's fairly arbitrary - as long as they aren't in your public html directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Immutable functional objects in highly mutable domain I'm currently learning functional programming in my spare time with Scala, and I have an idle newbie question.
I can see the elegance of having immutable objects when doing something like calculating a Haar wavelet transform - i.e. when the data itself being represented by the objects doesn't change.
But I saw a blog where someone had a small game as an example when demonstrating immutability. If a creature object recieved damage, it didn't change its state - it returned a new creature object with the new hitpoints and a new "aggro towards X" flag. But if we were to design something like a MMORPG, World of Warcraft say. A hundred players in a battleground... possibly thousands of attacks and buffing/debuffing spell effects affecting them in different ways. Is it still possible to design the system with completely immutable objects? To me it would seem like there would be a ginormous swarm of new instances each 'tick'. And to get the currently valid instance of objects, all clients would constantly have to go through some sort of central "gameworld" object, or?
Does functional programming scale for this, or is this a case of "best tool for best job, probably not immutable here"?
A: Typically in functional programming you won't have C++ style constructors. Then, even though conceptually you are creating objects all the time, it doesn't mean that the compiler has to make code to allocate a new object, because it can't affect the behaviour of the program. Since the data is immutable, the compiler can see what values you've just specified, and what has been passed into your functions.
Then, the compiler can create really tight compiled code that just calculates the fields in the specific objects when they are needed. How well this works depends on the quality of the compiler you use. However, clean functional programming code tells the compiler quite a lot more about your code than a C compiler for a similar program could assume, and so therefore a good compiler may generate better code than what you might expect.
So, at least in theory, there's no reason to be concerned; functional programming implementations can scale just as well as object oriented heap allocate implementations. In practice, you need to understand the quality of the language implementation you are working with.
A: An MMORPG is already an example of immutability. Since the game is distributed across servers and gamers' systems, there is absolutely not a central "gameworld" object. Thus, any object that gets sent over the wire is immutable — because it doesn't get changed by the receiver. Instead, a new object or message gets sent as a response, if there is one.
I've never written a distributed game so I don't know exactly how they're implemented, but I suspect that updates to objects are either computed locally or sent as diffs over the wire.
For example, you're playing Command & Conquer. Your mammoth tank is sitting in ready mode guarding your base. Your opponent approaches with a light tank to explore your base. Your mammoth tank shoots and hits your opponent's tank, causing damage.
This game is pretty simple, so I suspect a lot is computed locally whenever possible. Assume the two players' computers are initially in sync in terms of game state. Then your opponent clicks to move his light tank into your base. A message (immutable) is sent to you over the wire. Since the algorithm to move a tank is (probably) deterministic, your copy of Command & Conquer can move your opponent's tank on your screen, updating your game state (could be immutable or mutable). When the light tank comes in range of your mammoth tank, your tank fires. A random value is generated on the server (in this case, one computer is chosen arbitrarily as the server) to determine whether the shot hits your opponent or not. Assuming the tank was hit and an update to your opponent's tank must be made, only the diff — the fact that the tank's new armor level has decreased to 22% — is sent over the wire to sync the two players' games. This message is immutable.
Whether the object on either player's computer representing the tank is mutable or immutable is irrelevant; it can be implemented either way. Each player does not directly change the state of other gamers' game.
A: One point to note on immutability is that (if implemented correctly) it makes object creation relatively lightweight. If a field is immutable, then it can be shared between instances.
A: It's important to consider when designing a functional program that, like you state, Immutable objects will have some overhead. It's also important to remember that by having objects in your MMORPG program be immutable it will be inherently more scalable. So, the initial investment in equipment may be higher, but down the road as things expand you will be able to scale to your player base.
Another important thing to consider is that right now a the beefiest machines have 6 cores per cpu. Consider a dual cpu machine with 6 cores each. One of these 12 cores can be doing garbage collection and so the overhead from tearing down lots of objects can be offset by the application being easily scalable to those other 11 cores.
Also remember that not every object (and it's sub objects) need to be completely rebuilt on a copy. Any reference type that didn't change will only take a single reference assignment when an object is "copied".
A: Don't think of object creation at the wire level. For example, an optimized runtime for a functional language will probably be able to "cheat" when it comes to replacing an object and actual do mutation of the existing struct, if it knows nothing will reference the original and the new one replaces it completely. Think of Tail Recursion Optimization, but applied to object state.
A: I found a blog today that deals EXACTLY with the questions I raised in this post:
http://prog21.dadgum.com/23.html
A:
To me it would seem like there would be a ginormous swarm of new instances each 'tick'.
Indeed, that is the case. I have a Haskell application that reads a market data feed (about five million messages over the course of a six-hour trading day, for the data in which we're interested) and maintains "current state" for various things, such as the most recent bid and offer prices and quantities for the instruments, how well our model fits the market, etc. etc. It's rather frightening to simulate a run of this program against a recorded feed in profiling mode and watch it allocate and GC close to 288 TB of memory (or close to 50,000 times the size of my machine's RAM) in the first 500 seconds of its run. (The figure would be considerably higher without profiling, since profiling not only slows down the application, but also forces it all to run on one core, as well.)
But keep in mind, the garbage collector in pure language implementations is optimized for this sort of behavior. I'm quite happy with the overall speed of my application, and I think that it's fairly demanding, in that we have to parse several hundred messages per second from the market feed, do some fairly extensive calculations to build our model, and use that model to generate orders to go to the exchange as quickly as possible.
A: Like pretty much every tool in programming, Immutable objects are powerful, but dangerous in the wrong situation. I think the game example is not a very good one or at least very contrived.
Eric Lippert has some interesting posts on the topic of immutability, and they're quite an interesting read.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Retrieve list of defined roles in java ee 5 I was wondering if it would be possible to retrieve the complete list of security roles defined in a web.xml file in the java code? And if so how to do it?
I am aware of the 'isUserInRole' method but I also want to handle cases where a role is requested but not defined (or spelled differently) in the web.xml file.
A: As far as I know, there's no way do do this within the Servlet API. However, you can parse web.xml directly and extract the values yourself. I used dom4j below, but you can use whatever XML processing stuff you like:
protected List<String> getSecurityRoles() {
List<String> roles = new ArrayList<String>();
ServletContext sc = this.getServletContext();
InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");
try {
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
Element webApp = doc.getRootElement();
// Type safety warning: dom4j doesn't use generics
List<Element> roleElements = webApp.elements("security-role");
for (Element roleEl : roleElements) {
roles.add(roleEl.element("role-name").getText());
}
} catch (DocumentException e) {
e.printStackTrace();
}
return roles;
}
A: Here is the version of Ian's answer using newer DOM API:
private List<String> readRoles() {
List<String> roles = new ArrayList<>();
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/web.xml");
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(is));
NodeList securityRoles = doc.getDocumentElement().getElementsByTagName("security-role");
for (int i = 0; i < securityRoles.getLength(); i++) {
Node n = securityRoles.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
NodeList roleNames = ((Element) n).getElementsByTagName("role-name");
roles.add(roleNames.item(0).getTextContent().trim()); // lets's assume that <role-name> is always present
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new IllegalStateException("Exception while reading security roles from web.xml", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
logger.warn("Exception while closing stream", e);
}
}
}
return roles;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you handle multiple selection in a drop down style control? I have a WinForms application with a view where the user selects a single time span from a list of predefined time spans in a ComboBox, with it's DropDownStyle property set to DropDownList.
Now, the requirements have changed. The users are going to need the ability to make multiple selections from the list of time spans.
Is it possible to make multiple selections in a ComboBox? How do you present those choices when the ComboBox is collapsed? Don't forget the usability aspect.
Does some other control exist (built in or 3rd party, preferrably a drop down of some sort) that can provide for my users needs?
Update: Misleading title...
A: I agree with @Thomas Owens on the usability aspect. If you are selecting multiple items then the user should be able to see all of the items that are selected. Maybe a checked list box will work for this.
If you still have you heart set on using a drop down type of control take a look at the DevExpress editors toolkit. I have just looked through their demo and there is a control called a PopupContainerEdit that will allow you to pop up a list of items with checkboxes. When the popup collapses you could always show the items as a coma delimited list. (though this may be unusable if the list is longer than the box)
A: Even if it is possible, I would suggest changing the input type. When I see a drop-down box, I think that I must pick one. The ability to (and even how to) pick multiple options might elude your user. A standard list box might be more appropriate, from a usability standpoint.
A: I dont think its possible out of the box without writing a bunch of custom code.
I would have to agree with Thomas, except would even suggest possibly using a checkedlistbox, as imo, it is more clear that multiple selections are to be made than a list box (and you dont need help text saying to multi select, use ctrl)
A: I would use the CheckedListBox instead. It visualizes the multiple selection and you are able to select multiple entries.
Here is the Microsoft link to the class.
A: The Windows.Forms.ComboBox cannot provide multi-selection.
A: You are looking for ListBox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: mod_python on CentOS under httpd and hsphere I have asked our hosting provider to add mod_python to our httpd server. The server appears to be in an hsphere cluster and they appear to use yum to administer it. He is reporting some dependencies missing and I do't quite understand how that could have come about.
versions (this is as much as I have been given):
CentOS 5
apache - 2 (but he's not sure about the exact version)
mod_python - 3.3.1
numpy - 1.1.1
scipy - 0.6.0
yum - 3.2.8
hsphere - 3.1 patch 1
The error he is reporting is as follows:
yum install mod_python
...
Package mod_python.i386 0:3.2.8-3.1 set to be updated
Processing Dependency: httpd >- 2.0.40 for package: mod_python
Processing Dependency: httpd-mmn = 20051115 for package: mod_python
Finished Dependency Resolution
Error: Missing Dependency: httpd >= 2.0.40 is needed by package mod_python
Error: Missing Dependency: httpd-mmn = 20051115 is needed by package mod_python
Not being a UNIX admin I only have a naive guess about this, but the message would seem to suggest that there is a version mismatch between httpd and mod_python rather than the dependencies being missing completely.
So my question is, what should I ask/tell the Administrator to do?
Is there something obviously wrong with the combination of components above?
A: We have mod_python 3.3 running on Apache 2.2 on a CentOS (forgot the version). All we did is download the tar.gz (from http://httpd.apache.org/modules/python-download.cgi) , extract it...
$ ./configure --with-apxs=/usr/local/apache2/bin/apxs
$ ./make
$ su
$ make install
Everything works fine. We couldn't use yum so everything is built from source.
My suggestion would be to try to build from source.
A: My first reaction would be to yum update apache (or just a yum update).
Then try the yum install mod_python.
A: also getting same issue
--> Running transaction check
---> Package mod_python.i386 0:3.2.8-3.1 set to be updated
--> Processing Dependency: httpd >= 2.0.40 for package: mod_python
--> Processing Dependency: httpd-mmn = 20051115 for package: mod_python
--> Finished Dependency Resolution
Error: Missing Dependency: httpd >= 2.0.40 is needed by package mod_python
Error: Missing Dependency: httpd-mmn = 20051115 is needed by package mod_python
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I build a webpage for printing so it won't split badly over pages? I have a web application that generates a long report and I need to print it. If I just print the page it will break at the end of the physical page. How can I calculate where to make a break in the web page so that the page breaks line up with the physical pages when they print?
A: We have a system which prints out invoices for selected orders which places a
<br style="page-break-before:always;">
between each invoice. This means each invoice goes on a new page.
It's also good practice to use a print stylesheet
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
which can hide/display relevant areas of the page. No point printing out leftnav links etc when someone wants the actual page contents.
A: *
*Paged media
*Print Reference
*
*page-break-after (MDN)
*page-break-before (MDN)
*page-break-inside (MDN)
A: I usually avoid web page (HTML) printing all together. If formatted printing is required, I generate PDF or CSV/Spreadsheet formats for my customers to print in any way they want.
I usually generate print for global use, meaning that all types of settings differ (eg. paper size: Legal, Letter, A4, etc) from workplace to workplace. I've found it to be too big a task to guarantee esthetic output everywhere.
A: There is a css property to attempt to ensure the position of page-breaks. You can give an element the rule page-break-before: always or page-break-after: always` to indicate whether the break should be before or after the element. This has pretty poor support across browsers and I wouldn't rely on it. See http://www.w3schools.com/CSS/pr_print_pageba.asp for more details.
A: Either with CSS page-break-before/after
Other ways:
*
*use JasperReports and load the data in a report, instead of a html page
*use Apache FOP with XSL to translate your HTML (or the raw data) to FOP and later to PDF
Both methods are quite extensive, so if you don't want to spend some effort better directly skip to another answer....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: additional fields in NHibernate many-to-many relation tables when i have a many-to.many relation with nhibernate and let nhibernate generate my db schema, it adds an aditional table that contains the primary keys of the related entities.
is it possible to add additional fields to this and access them without having to hassle around with sql manually?
A: I don't think thats possible. If you are saying that the relation has some state than in essence it is an object in it's own right and should be treated (mapped) as such.
A: Agree with Jasper. What you are modeling in that case is not a relation but an entity itself, with 1-N and N-1 relations to the other two entities.
It is not that NHibernate cannot handle it, it is that you simply cannot model it.
A: In this case, how would you build the in the mapping file for the new entity (that acts as the bridge between the two initial tables) ? In my case this link table has two foreign keys (int), one for each initial table, plus some other fields (startDate, endDate)
The thing is, in my new entity, I do not have properties for these two foreign keys. I only have one property that is of the type of the entity the foreign key is pointing to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Clearing a list I find it annoying that I can't clear a list. In this example:
a = []
a.append(1)
a.append(2)
a = []
The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.
The only way I can see of retaining the same pointer is doing something like the following:
for i in range(len(a)):
a.pop()
This seems pretty long-winded though, is there a better way of solving this?
A: I'm not sure why you're worried about the fact that you're referencing a new, empty list in memory instead of the same "pointer".
Your other list is going to be collected sooner or later and one of the big perks about working in a high level, garbage-collected language is that you don't normally need to worry about stuff like this.
A: You are looking for:
del L[:]
A: this can help you::)
L[:] = []
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What would a Log4Net Wrapper class look like? I have been looking for a logging framework for .net (c#) and decided to give log4net a go after reading up on a few question/answer threads here on stackoverflow. I see people mentioning over and over that they use a wrapper class for log4net and I am wonder what that would look like.
I have my code split up into different projects (data access/business/webservice/..).
How would a log4net wrapper class look like? Would the wrapper class need to be included in all of the projects? Should I build it as a separate project all together?
Should the wrapper be a singleton class?
A: Essentially you create an interface and then a concrete implementation of that interface that wraps the classes and methods of Log4net directly. Additional logging systems can be wrapped by creating more concrete classes which wrap other classes and methods of those systems. Finally use a factory to create instances of your wrappers based on a configuration setting or line of code change. (Note: you can get more flexible - and complex - using an Inversion of Control container such as StructureMap.)
public interface ILogger
{
void Debug(object message);
bool IsDebugEnabled { get; }
// continue for all methods like Error, Fatal ...
}
public class Log4NetWrapper : ILogger
{
private readonly log4net.ILog _logger;
public Log4NetWrapper(Type type)
{
_logger = log4net.LogManager.GetLogger(type);
}
public void Debug(object message)
{
_logger.Debug(message);
}
public bool IsDebugEnabled
{
get { return _logger.IsDebugEnabled; }
}
// complete ILogger interface implementation
}
public static class LogManager
{
public static ILogger GetLogger(Type type)
{
// if configuration file says log4net...
return new Log4NetWrapper(type);
// if it says Joe's Logger...
// return new JoesLoggerWrapper(type);
}
}
And an example of using this code in your classes (declared as a static readonly field):
private static readonly ILogger _logger =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
You can get the same slightly more performance friendly effect using:
private static readonly ILogger _logger =
LogManager.GetLogger(typeof(YourTypeName));
The former example is considered more maintainable.
You would not want to create a Singleton to handle all logging because Log4Net logs for the invoking type; its much cleaner and useful to have each type use its own logger rather than just seeing a single type in the log file reporting all messages.
Because your implementation should be fairly reusable (other projects in your organization) you could make it its own assembly or ideally include it with your own personal/organization's framework/utility assembly. Do not re-declare the classes separately in each of your business/data/UI assemblies, that's not maintainable.
A: What benefits are you planning on getting out of writing a wrapper for log4net. I'd recommend getting comfortable with the log4net classes first before writing a wrapper around them. cfeduke is right in his answer on how to write said wrapper, but unless you need to add actual functionality to his example a wrapper would only succeed in slowing the logging process down and adding complexity for future maintainers. This especially true when refactoring tools available in .Net make such changes super easy.
A: Assuming you were going with something like cfeduke's answer above, you could also add an overload to your LogManager like this:
public static ILogger GetLogger()
{
var stack = new StackTrace();
var frame = stack.GetFrame(1);
return new Log4NetWrapper(frame.GetMethod().DeclaringType);
}
That way in your code you can now just use:
private static readonly ILogger _logger = LogManager.GetLogger();
instead of either of these:
private static readonly ILogger _logger =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger _logger =
LogManager.GetLogger(typeof(YourTypeName));
Which is effectively equivalent of the first alternative (i.e. the one that uses MethodBase.GetCurrentMethod().DeclaringType), only a little simpler.
A: My understanding is that a wrapper class for log4net would be a static class which takes care of initializing the logging object from app.config/web.config or by code (e.g. integration with NUnit).
A: I have successfully isolated log4net dependency into a single project. If you intend to do the same, here is what my wrapper class look like:
using System;
namespace Framework.Logging
{
public class Logger
{
private readonly log4net.ILog _log;
public Logger()
{
_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
public Logger(string name)
{
_log = log4net.LogManager.GetLogger(name);
}
public Logger(Type type)
{
_log = log4net.LogManager.GetLogger(type);
}
public void Debug(object message, Exception ex = null)
{
if (_log.IsDebugEnabled)
{
if (ex == null)
{
_log.Debug(message);
}
else
{
_log.Debug(message, ex);
}
}
}
public void Info(object message, Exception ex = null)
{
if (_log.IsInfoEnabled)
{
if (ex == null)
{
_log.Info(message);
}
else
{
_log.Info(message, ex);
}
}
}
public void Warn(object message, Exception ex = null)
{
if (_log.IsWarnEnabled)
{
if (ex == null)
{
_log.Warn(message);
}
else
{
_log.Warn(message, ex);
}
}
}
public void Error(object message, Exception ex = null)
{
if (_log.IsErrorEnabled)
{
if (ex == null)
{
_log.Error(message);
}
else
{
_log.Error(message, ex);
}
}
}
public void Fatal(object message, Exception ex = null)
{
if (_log.IsFatalEnabled)
{
if (ex == null)
{
_log.Fatal(message);
}
else
{
_log.Fatal(message, ex);
}
}
}
}
}
And dont forget to add this in the AssemblyInfo.cs of the interfacing project (took me a good few hours to find this)
[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "log4net.config")]
And put your log4net configuration xml in log4net.config file, set it as Content, Copy Always
A: There are frameworks like the Prism Library for WPF that promote the usage of a facade for the logging framework of your choice.
This is an example that uses log4net:
using System;
using log4net;
using log4net.Core;
using Prism.Logging;
public class Log4NetLoggerFacade : ILoggerFacade
{
private static readonly ILog Log4NetLog = LogManager.GetLogger(typeof (Log4NetLoggerFacade));
public void Log(string message, Category category, Priority priority)
{
switch (category)
{
case Category.Debug:
Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Debug, message, null);
break;
case Category.Exception:
Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Error, message, null);
break;
case Category.Info:
Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Info, message, null);
break;
case Category.Warn:
Log4NetLog.Logger.Log(typeof(Log4NetLoggerFacade), Level.Warn, message, null);
break;
default:
throw new ArgumentOutOfRangeException(nameof(category), category, null);
}
}
}
Note that by specifying the callerStackBoundaryDeclaringType you can still get the class name of the caller issuing the logging request. All you need to do is to include %C %M in your conversion pattern:
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %C.%M - %message%newline" />
</layout>
However, as the documentation warns, generating the caller class information is slow, therefore it must be used wisely.
A: a possible use for a log4net wrapper could be a class that gets the calling class and method via reflection to get an idea of where your logging entry happened. at least i use this frequently.
A: Alconja, I like your idea of using the stacktrace to jump back to the calling method. I was thinking of further encapsulating the calls, to not just retrieve the logger object, but to perform actually perform the logging. What I want is a static class that handles the logging, by abstracting from the specific implementation used. I.e.
LoggingService.LogError("my error message");
That way I only need to change the internals of the static class, if I later decide to user another logging system.
So I used your idea to get the calling object using the stack trace :
public static class LoggingService
{
private static ILog GetLogger()
{
var stack = new StackTrace();
var frame = stack.GetFrame(2);
return log4net.LogManager.GetLogger(frame.GetMethod().DeclaringType);
}
public static void LogError(string message)
{
ILog logger = GetLogger();
if (logger.IsErrorEnabled)
logger.Error(message);
}
...
}
Does anybody see a problem with this approach?
A: I know this answer is late, but it may help someone in the future.
It sounds like you want a programmatic API that XQuiSoft Logging gives you. You don't have to specify which logger you want with XQuiSoft. it is as simple as this:
Log.Write(Level.Verbose, "source", "category", "your message here");
Then via configuration you direct messages by source, category, level, or any other custom filter to different locations (files, emails, etc...).
See this article for an introduction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: Performance of System.IO.ReadAllxxx / WriteAllxxx methods Is there any performance comparison of System.IO.File.ReadAllxxx / WriteAllxxx methods vs StreamReader / StremWriter classes available on web. What you think is the best way(from a performance perspective) to read/write text files in .net 3.0?
When I checked the MSDN page of System.IO.File class, in the sample code MS is using StreamReader / StreamWriter for file operations. Is there any specific reason for avoiding File.ReadAllxxx / WriteAllxxx methods, even though they look much easier to understand?
A: You probably don't want to use File.ReadAllxxx / WriteAllxxx if you have any intention to support loading / saving of really large files.
In other words, for an editor which you intend to remain usable when editing gigabyte size files, you want some design with StreamReader/StreamWriter and seeking, so you load only the part of the file that is visible.
For anything without these (rare) requirements, I'd say take the easy route and use File.ReadAllxxx / WriteAllxxx. They just use the same StreamReader/Writer pattern internally as you'd code by hand anyway, as aku shows.
A: The File.ReadAllText and similar methods use StreamReader/Writers internally, so performance should be comparable to whatever you do yourself.
I'd say go with the File.XXX methods whenever possible, it makes your code a) easier to read b) less likely to contain bugs (in any impl you write yourself).
A: Unless you are doing something such as applying a regular expression that is multiline matching to a text file you generally want to avoid the ReadAll/WriteAll. Doing things in smaller more manageable chunks will almost always result in better performance.
For example, reading a table from a database and sending it to a client's web browser should be done in small sets that utilize the nature of small network messages and reduce the usage of the processing computer's memory. There's no reason to buffer 10,000 records in memory on the web server and dump it all at once. Same thing goes for file systems. If you are concerned with write performance of many small amounts of data - such as what goes on in the underlying file system for allocating space and what's the overhead - you may find these articles enlightening:
Windows File Cache Usage
File Read Benchmarks
Clarification: if you are doing a ReadAll followed by a String.Split('\r') to get an array of all the lines in the file, and the using a for loop to process each line that's code which will generally result in worse performance than reading the file line by line and performing your process on each line. This isn't a hard rule - if you have some processing that takes a large chunk of time its often better to release system resources (the file handle) sooner than later. However in regards to writing files its almost always better to dump the results of any transformative process (such as invoking ToString() on a large list of items) per item than buffering it in memory.
A: This MSR (Microsoft Research) paper is a good start, they also document a number of point tools like, IOSpeed, FragDisk, etc... which you can use and test in your envrionment.
There is also an updated report/presentation you can read about how to maximise sequential IO. Very interesting stuff as they debunk, the "moving the HD head is the most time consuming operation" myth, they also document fully their test envrionments and associated configurations, down to the motherboard, raid controller and virtually any relivent information for you to replicate their work. Some of the highlights are how an Opteron / XEON matched up, but they then also compared them to an insane\hype NEC Itanium (32 or 64 proc or something) for measure. From the second link here you can find a lot more resources around how to test and evaluate high-throughput scenerio's and needs.
Some of the other MSR paper's in this same research topic involve guidieance about where to maximise your spending, (e.g. RAM, CPU, Disk Spindals... etc..) to accomidate your usage patterns... all very neat.
However some of it is dated, but usually older-API's are the faster/low-level ones anyhow ;)
I currently push hundreds of thousands of TPS on a purpose built app server, using a mix of C#, C++/CLI, native code and bitmap Caching (rtl*bitmap).
Take care;
A: @Fredrik Kalseth is right. File.ReadXXX methods are just convenient wrappers around StreamReader class.
For example here is an implementation of File.ReadAllText
public static string ReadAllText(string path, Encoding encoding)
{
using (StreamReader reader = new StreamReader(path, encoding))
{
return reader.ReadToEnd();
}
}
A: The others have explained the performance so I won't add to it, however I will add that it is likely that the MSDN code sample was written before .NET 2.0 when the helper methods were not available.
A: This link has benchmarks for reading 50+K Lines, and indicates that a streamreader is about 40% faster.
http://dotnetperls.com/Content/File-Handling.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use Maven Modules without svn:externals? I have never quite understood how/why I would use Maven modules (reactor builds).
We have tens of libraries that we share (as dependencies) among our products, and between libraries as well. If we were to switch to making them Maven modules, how would we set it up, both in SVN and in our working copies?
Do Maven modules really need to be subfolders? Do they need to be subfolders in the SVN repo too?
Assuming you just need subfolders in the working copy, I suppose svn:externals would work to make, say, a "util" library be a module of multiple projects at the same time. But I've read many bad things about using svn:externals because there is nothing to stop you from modifying the code in the external, but its not tracked.
Any suggestions? Am I missing the boat on modules?
A: No ... a modular project should only be used when the child project is integrated into the parent to create a larger artifact, so an example might be an Enterprise project, where your modules contain the EJB (server and client), the WAR, and then those are combined into an EAR file. This modularity is only for convenience and can be skipped if preferred.
In the case of reusable libraries, make them independent projects and deploy them to a shared repository. Then they must be referenced as dependencies in the project using them.
A: I guess that's a problem with subversion. Which forces you to create a folder structure for branching. Other version control systems allow branching without visibility in the folder structure, where maven modules can be created more easily.
I work with a product of more than 250 modules, and they reside in "logical" maven modules that only signify an area of functioning. e.g. "CoreService", "Utilities" and "Applications". We are very happy with using maven modules for this, since we can make sure that all CoreServices use a certain version of a certain dependency and that all applications get a certain aspectJ library woven into them.
For your solution though:
There is a feature in subversion for a module to find its parent called relativePath which is a tag in the parent tag. The only reason to put sub-projects in its parent's folder is so that they can be put in the reactor when building the parent. The child projects can still be built (and installed) individually.
There's also enhanced support for svn:externals in subersion 1.5 which allows relative URL:s, which should also come in handy in this case.
-Good luck and report back here if you find a solution!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: msbuild: set a specific preprocessor #define in the command line In a C++ file, I have a code like this:
#if ACTIVATE
# pragma message( "Activated" )
#else
# pragma message( "Not Activated")
#endif
I want to set this ACTIVE define to 1 with the msbuild command line.
It tried this but it doesn't work:
msbuild /p:DefineConstants="ACTIVATE=1"
Any idea?
A: Use the CL environment variable to define preprocessor macros
Before calling MSBUILD, simply set the environment variable 'CL' with '/D' options like so:
set CL=/DACTIVATE to define ACTIVATE
You can use the '#' symbol to replace '=' sign
set CL=/DACTIVATE#1 will define ACTIVATE=1
Then make the call to MSBUILD
More documentation on the CL Environment Variables can be found at:
https://msdn.microsoft.com/en-us/library/kezkeayy(v=vs.140).aspx
A: Our solution was to use an environment variable with /D defines in it, combined with the Additional Options box in visual studio.
*
*In Visual Studio, add an environment variable macro, $(ExternalCompilerOptions), to the Additional Options under project options->C/C++->Command Line (remember both Debug and Release configs)
*Set the environment variable prior to calling msbuild. Use the /D compiler option to define your macros
c:\> set ExternalCompilerOptions=/DFOO /DBAR
c:\> msbuild
Item #1 ends up looking like this in the vcxproj file:
<ClCompile>
<AdditionalOptions>$(ExternalCompilerOptions) ... </AdditionalOptions>
</ClCompile>
This works for me with VS 2010. We drive msbuild from various build scripts, so the environment variable ugliness is hidden a bit. Note that I have not tested if this works when you need to set the define to specific value ( /DACTIVATE=1 ). I think it would work, but I'm concerned about having multiple '='s in there.
H^2
A: C++ projects (and solutions) are not (yet ?) integrated in the MSBuild environment. As part of the build process, the VCBuild task is called, which is just a wrapper around vcbuild.exe.
You could :
*
*create a specific configuration for your solution where ACTIVATE=1 would be defined, and compile it with devenv.exe (with the /ProjectConfig switch).
*create your own target file to wrap your own call to the VCBuild task (see the Override parameter)...
*use vcbuild.exe instead of msbuild.exe. (vcbuild.exe does not seem to have the equivalent of an Override parameter).
Note that your solution would not work for C# projects either unless you tweaked your project files a bit. For reference, here is how I would do this :
*
*Add the following code before the call to <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> :
<PropertyGroup Condition=" '$(MyConstants)' != '' ">
<DefineConstants>$(DefineConstants);$(MyConstants)</DefineConstants>
</PropertyGroup>
*
*Call MSBuild like this :
msbuild /p:MyConstants="ACTIVATE=1"
A: If you need to define some constant (not just true/false), you can do it the following way:
On command line:
MSBuild /p:MyDefine=MyValue
In vcxproj file (in section <ClCompile>; and/or <ResourceCompile>, depending on where you need it):
<PreprocessorDefinitions>MY_DEFINE=$(MyDefine);$(PreprocessorDefinitions)</PreprocessorDefinitions>
Note that if you don't specify /p:MyDefine=MyValue in a call to MSBuild then empty string will be assigned to MY_DEFINE macro. If it's OK for you, that's it. If not, keep reading.
How to make a macro undefined if corresponding MSBuild parameter is not specified
To have MY_DEFINE macro undefined instead of empty string, you can use the following trick:
<ClCompile>
....
<PreprocessorDefinitions>_DEBUG;_CONSOLE;OTHER_UNCONDITIONAL_MACROS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions Condition="'$(MyDefine)'!=''">MY_DEFINE=$(MyDefine);%(PreprocessorDefinitions)</PreprocessorDefinitions>
....
</ClCompile>
First PreprocessorDefinitions defines unconditional macros. Second PreprocessorDefinitions additionally defines MY_DEFINE macro when MyDefine is not empty string. You can test this by placing the following piece of code into your cpp file:
#define STRINGIZE2(x) #x
#define STRINGIZE(x) STRINGIZE2(x)
#ifndef MY_DEFINE
#pragma message("MY_DEFINE is not defined.")
#else
#pragma message("MY_DEFINE is defined to: [" STRINGIZE(MY_DEFINE) "]")
#endif
and running:
> MSBuild SandBox.sln /p:Configuration=Debug /p:MyDefine=test /t:Rebuild
...
MY_DEFINE is defined to: [test]
...
> MSBuild SandBox.sln /p:Configuration=Debug /p:MyDefine= /t:Rebuild
...
MY_DEFINE is not defined.
...
> MSBuild SandBox.sln /p:Configuration=Debug /t:Rebuild
...
MY_DEFINE is not defined.
...
A: I think you want:
/p:DefineConstants=ACTIVATE
A: Maybe it is a bad idea to answer such old question, but recently I googled a similar problem and found this topic. I wrote a cmd script for some build system and I was succeed to find a solution. I leave it here for future generations (:
According to @acemtp's problem, my solution would look like this:
@echo off
:: it is considered that Visual Studio tools are in the PATH
if "%1"=="USE_ACTIVATE_MACRO" (
:: if parameter USE_ACTIVATE_MACRO is passed to script
:: the macro ACTIVATE will be defined for the project
set CL=/DACTIVATE#1
)
call msbuild /t:Rebuild /p:Configuration=Release
UPD: I tried to use set CL=/DACTIVATE=1 and it also worked, but the official documentation recommends to use number sign
A: The answer is : YOU CANNOT
A: It should probably be:
#ifdef ACTIVATE
# pragma message( "Activated" )
#else
# pragma message( "Not Activated")
#endif
A: I needed to do this too - needed to be able to build two different versions of my app and wanted to be able to script the build using VCBUILD. VCBUILD does have the /override command line switch, but I am not sure it can be used to modify #define symbols that can then be tested using #if conditional compilation.
The solution I cam up with was to write a simple utility to create a header file that #defined the symbol based on the state of an environment variable and run the utility from a pre-build step. Prior to each execution of the VCBUILD step the script sets the environment variable and "touches" a file in the app to ensure that the prebuild step is executed.
Yes, it is an ugly hack, but it was the best I could come up with!
A: For VS2010 and up, see my answer here for a solution that requires no modification of the original project file.
A: As @bigh_29 has mentioned, using environment variables to define or undefine a preprocessor.
What he suggested the way to undefine a preprocessor is actually /UACTIVATE.
This way, any preprocessor matching ACTIVATE will be negated and compiler wouldn't go through your #if ACTIVATE #endif enclosure.
A: I got pretty fed up with trying to do this without modifying solution or project files so I came up with the following:
*
*Create empty file as part of build e.g. feature_flag.h
*Replace #if FEATURE_FLAG with #if !__has_include("feature_flag.h")
*Remove feature_flag.h at the end of the build
It's not using #define but it does use the preprocessor which was what I needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: PHP - Custom error handling. Redirected 404 is being hijacked by AVG Anti-Virus. How to stop? I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages.
e.g. http://metachat.org/recent
I've a feeling this is a bad way of doing this, but it's code I inherited...
Although the page displays correctly on most browsers, I'm getting a situation where AVG Anti-Virus is hijacking the page and redirecting it to an offsite 404 page.
I've tried to force a header (Status: 200 OK) using the header command in PHP, but if I do a curl -I of the page, I get the following...
HTTP/1.1 404 Not Found
Date: Fri, 03 Oct 2008 11:43:01 GMT
Server: Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 PHP/4.3.10-16 mod_ssl/2
.0.54 OpenSSL/0.9.7e
X-Powered-By: PHP/4.3.10-16
Status: 200 OK
Content-Type: text/html
I guess that first line is the line AVG traps for its forced redirect.
Without rewriting the software to use Mod_rewrite (which I don't really understand), how can I (in PHP) stop the "HTTP:/1/1 404 Not Found" line being sent in the headers when displaying this page?
Thanks.
A: There's no way other than using URL rewriting (mod_rewrite) or creating the missing pages. What's happening is that the client requests a page which doesn't exist. Apache is configured to serve a special page upon 404 errors, but it still sends the 404 status code, then AVG traps that.
So, you could do something like:
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteRule (.*) index.php?missing_content=$1
That will rewrite everything that doesn't exist (and would thus give a 404) to your index.php with the URL path in the missing_content query string parameter
A: If what you get is a Page Not Found error, don't make it send Status 200 OK. Please.
It's one of most annoying "tricks" people do for whatever reason. If the page user requests does not exist, tell this to him, as well as to his browser. And to search engines, that otherwise will crawl/cache your custom error-page thinking it's the actual response.
If someone has some software installed that displays something else instead of your 404, it's his own problem and don't try to fight it making your service lie to the browser :)
A: Some browsers don't display the content of 404 pages if that content is quite small. If there's larger page content they do display it. This rule varies per browser. Try adding more content to your 404 page and see whether that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: detect svn changes in a .bat I have a .bat and inside the .bat i would like to execute a special code if there's some modification inside the svn repository (for example, compile).
A: For Win 2000 and later, this would assign the last output row from the svn status commmand to the svnOut variable and then test if the variable contains anything:
@echo off
set svnOut=
set svnDir=C:Your\path\to\svn\dir\to\check
for /F "tokens=*" %%I in ('svn status %svnDir%') do set svnOut=%%I
if "%svnOut%"=="" (
echo No changes
) else (
echo Changed files!
)
Why there is a line like this
set svnOut=
you have to figure out yourself. ;-)
A: Ok, the solution I found with the help of Tooony:
set vHEAD = 0
set vBASE = 0
set svnDir=<path to local svn directory>
for /F "tokens=1,2" %%I in ('svn info -r HEAD %svnDir%') do if "%%I"=="Revision:" set vHEAD=%%J
for /F "tokens=1,2" %%I in ('svn info -r BASE %svnDir%') do if "%%I"=="Revision:" set vBASE=%%J
if "%vBASE%"=="%vHEAD%" (
echo No changes
) else (
echo Changed files!
)
A: Have your .bat execute svnversion (if you're using Subversion) or SvnWCRev.exe (if you're using TortoiseSVN) against the top-most level of your working copy.
Both output if your working copy has been modified.
svnversion appends a "M" to its output.
SvnWCRev.exe will print a line of text that the WC has been modified.
A: Are you wanting this to be reactive? Or, on-demand?
For reactive, see hooks. The script will have to be named according to it's purpose: pre-commit.bat, post-commit.bat. The scripts are called as: [script] [repos-path] [revision-number]
For, on-demand:
*
*Working Copy
*
*svn log
*svn st
*svn diff
*svn proplist
*Repository
*
*svnlook author
*svnlook changed
*svnlook date
*svnlook diff
*svnlook history
Example:
svn st "C:\path\to\working\directory\" >> C:\path\to\working\project.log
Every time you run the BAT, it'll add the st output to project.log. Adjust as needed.
A: This version is based on @tooony's but checks the server for updates instead of the client.
@echo off
set svnOut=
rem Check svn server status of current working directory repository and see if first or second token is an *
for /F "tokens=1" %%I in ('svn status --show-updates') do if "%%I"=="*" set svnOut=%%I
rem echo "%svnOut%"
if "%svnOut%"=="" (
echo No changes
) else (
echo Changed files!
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I wrap a call to an .exe (with arguments) with another .exe? I have a Windows executable (say program.exe) and I want to provide users with 2 launchers that will pass different arguments to it.
program.exe -a
program.exe -b
I can easily do this with 2 batch files, but I would rather provide users with 2 .exe files as they are more likely to be used correctly without editing.
Is there an easy way to create such an executable?
A: Why create new executables?
Why not just create desktop shortcuts to launch the single exe.
A: You might try this: http://www.abyssmedia.com/quickbfc/
If you want something really, really small, you'd probably need to make your own Pascal/C program. I suggest Pascal because there is a very nice free compiler that produces really small .EXEs without the need to used a tweaked library (that would be the only C shortcoming in this case).
Cheers.
A: Not sure if its exactly what your trying to do but check this for possible solutions.
That answers the question in the title, as for what you write here, why dont you just parse the arguments and depending on them have the two functionalities inside one executable ?
A: If you have the source code to your application, you can change its behavior based on the name of the executable. It's not hard - in main, look at argv[0] and change the options based on that.
A: If you are using .Net you can read the information presented as parameters from another application or batch file. It's part of the Framework. Here it is is VB.NET
For Each Arg As String In Environment.GetCommandLineArgs()
//Process the arguments
Next Arg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UTF-8 in Windows How do I set the code page to UTF-8 in a C Windows program?
I have a third party library that uses fopen to open files. I can use wcstombs to convert my Unicode filenames to the current code page, however if the user has a filename with a character outside the code page then this breaks.
Ideally I would just call _setmbcp(65001) to set the code page to UTF-8, however the MSDN documentation for _setmbcp states that UTF-8 is not supported.
How can I get around this?
A: 2018 update: Windows 10 has made the "65001" code page less "pseudo" in two steps:
*
*conhost changes: Windows Subsystem for Linux uses code page 65001 for its consoles. It is also possible to run chcp 65001 in cmd.exe since WSL. (It has caused some pretty dumb Python bugs.)
*full-featured locale: Windows since build 17035 allows setting UTF-8 as the locale codepage. This is available from the April 2018 update.
A: Unfortunately, there is no way to make Unicode the current codepage in Windows. The CP_UTF7 and CP_UTF8 constants are pseudo-codepages, used only in MultiByteToWideChar and WideCharToMultiByte conversion functions, like Ben mentioned.
Your problem is similar to that of the fstream C++ classes. The fstream constructors accept only char* names, making impossible to open a file with a true Unicode name. The only solution offered by VC was a hack: open the file separately and then set the handle to the stream object. I'm afraid this isn't an option for you, of course, since the third party library probably doesn't accept handles.
The only solution I can think of is to create a temporary file with a non-Unicode name, which is hard-linked to the original, and use that as a parameter.
A: All Windows APIs think in UTF-16, so you're better off writing a wrapper around your library that converts at the boundaries.
Oddly enough, Windows thinks UTF-8 is a codepage for the purposes of conversion, so you use the same APIs as you would to convert between codepages:
std::wstring Utf8ToUtf16(const char* u8string)
{
int wcharcount = strlen(u8string);
wchar_t *tempWstr = new wchar_t[wcharcount];
MultiByteToWideChar(CP_UTF8, 0, u8string, -1, tempWstr, wcharcount);
wstring w(tempWstr);
delete [] tempWstr;
return w;
}
And something of similar form to convert back.
A: Use cygwin (which provides a UTF-8 locale by default), or write your own libc hack for Windows that does the necessary UTF-8 to UTF-16 translations and wraps the nonstandard _wfopen etc. functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Finding local IP addresses using Python's stdlib How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?
A: I'm afraid there aren't any good platform independent ways to do this other than connecting to another computer and having it send you your IP address. For example: findmyipaddress. Note that this won't work if you need an IP address that's behind NAT unless the computer you're connecting to is behind NAT as well.
Here's one solution that works in Linux: get the IP address associated with a network interface.
A: FYI I can verify that the method:
import socket
addr = socket.gethostbyname(socket.gethostname())
Works in OS X (10.6,10.5), Windows XP, and on a well administered RHEL department server. It did not work on a very minimal CentOS VM that I just do some kernel hacking on. So for that instance you can just check for a 127.0.0.1 address and in that case do the following:
if addr == "127.0.0.1":
import commands
output = commands.getoutput("/sbin/ifconfig")
addr = parseaddress(output)
And then parse the ip address from the output. It should be noted that ifconfig is not in a normal user's PATH by default and that is why I give the full path in the command. I hope this helps.
A: One simple way to produce "clean" output via command line utils:
import commands
ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +
"awk {'print $2'} | sed -ne 's/addr\:/ /p'")
print ips
It will show all IPv4 addresses on the system.
A: import socket
[i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)]
A: I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
This assumes you have an internet access, and that there is no local proxy.
A: import socket
socket.gethostbyname(socket.gethostname())
This won't work always (returns 127.0.0.1 on machines having the hostname in /etc/hosts as 127.0.0.1), a paliative would be what gimel shows, use socket.getfqdn() instead. Of course your machine needs a resolvable hostname.
A: If the computer has a route to the Internet, this will always work to get the preferred local ip address, even if /etc/hosts is not set correctly.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets
local_ip_address = s.getsockname()[0]
A: Socket API method
see https://stackoverflow.com/a/28950776/711085
Downsides:
*
*Not cross-platform.
*Requires more fallback code, tied to existence of particular addresses on the internet
*This will also not work if you're behind a NAT
*Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server)
*Make sure you make the destination address UNREACHABLE, like a numeric IP address that is spec-guaranteed to be unused. Do NOT use some domain like fakesubdomain.google.com or somefakewebsite.com; you'll still be spamming that party (now or in the future), and spamming your own network boxes as well in the process.
Reflector method
(Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.)
You can query some site like whatismyip.com (but with an API), such as:
from urllib.request import urlopen
import re
def getPublicIp():
data = str(urlopen('http://checkip.dyndns.com/').read())
# data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'
return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
or if using python2:
from urllib import urlopen
import re
def getPublicIp():
data = str(urlopen('http://checkip.dyndns.com/').read())
# data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'
return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
Advantages:
*
*One upside of this method is it's cross-platform
*It works from behind ugly NATs (e.g. your home router).
Disadvantages (and workarounds):
*
*Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure.
*Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server)
edit: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question "what is the internet?". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for gateways and routes. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that ("is it the network card, or the ethernet cable, which we're talking about?"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.
A: This will work on most linux boxes:
import socket, subprocess, re
def get_ipv4_address():
"""
Returns IP address(es) of current machine.
:return:
"""
p = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
ifc_resp = p.communicate()
patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
resp = patt.findall(ifc_resp[0])
print resp
get_ipv4_address()
A: This answer is my personal attempt to solve the problem of getting the LAN IP, since socket.gethostbyname(socket.gethostname()) also returned 127.0.0.1. This method does not require Internet just a LAN connection. Code is for Python 3.x but could easily be converted for 2.x. Using UDP Broadcast:
import select
import socket
import threading
from queue import Queue, Empty
def get_local_ip():
def udp_listening_server():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('<broadcast>', 8888))
s.setblocking(0)
while True:
result = select.select([s],[],[])
msg, address = result[0][0].recvfrom(1024)
msg = str(msg, 'UTF-8')
if msg == 'What is my LAN IP address?':
break
queue.put(address)
queue = Queue()
thread = threading.Thread(target=udp_listening_server)
thread.queue = queue
thread.start()
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
waiting = True
while waiting:
s2.sendto(bytes('What is my LAN IP address?', 'UTF-8'), ('<broadcast>', 8888))
try:
address = queue.get(False)
except Empty:
pass
else:
waiting = False
return address[0]
if __name__ == '__main__':
print(get_local_ip())
A: If you're looking for an IPV4 address different from your localhost IP address 127.0.0.1, here is a neat piece of python codes:
import subprocess
address = subprocess.check_output(['hostname', '-s', '-I'])
address = address.decode('utf-8')
address=address[:-1]
Which can also be written in a single line:
address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]
Even if you put localhost in /etc/hostname, the code will still give your local IP address.
A: This method returns the "primary" IP on the local box (the one with a default route).
*
*Does NOT need routable net access or any connection at all.
*Works even if all interfaces are unplugged from the network.
*Does NOT need or even try to get anywhere else.
*Works with NAT, public, private, external, and internal IP's
*Pure Python 2 (or 3) with no external dependencies.
*Works on Linux, Windows, and OSX.
Python 3 or 2:
import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
# doesn't even have to be reachable
s.connect(('10.254.254.254', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
print(get_ip())
This returns a single IP which is the primary (the one with a default route). If you need instead all IP's attached to all interfaces (including localhost, etc), see something like this answer.
If you are behind a NAT firewall like your wifi router at home, then this will not show your public NAT IP, but instead your private IP on the local network which has a default route to your local WIFI router. If you instead need your external IP:
*
*running this function on THAT external device (wifi router), or
*connecting to an external service such as https://www.ipify.org/ that could reflect back the IP as it's seen from the outside world
... but those ideas are completely different from the original question. :)
A: On Linux:
>>> import socket, struct, fcntl
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sockfd = sock.fileno()
>>> SIOCGIFADDR = 0x8915
>>>
>>> def get_ip(iface = 'eth0'):
... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
... try:
... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
... except:
... return None
... ip = struct.unpack('16sH2x4s8x', res)[2]
... return socket.inet_ntoa(ip)
...
>>> get_ip('eth0')
'10.80.40.234'
>>>
A: 127.0.1.1 is your real IP address. More generally speaking, a computer can have any number of IP addresses. You can filter them for private networks - 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
However, there is no cross-platform way to get all IP addresses. On Linux, you can use the SIOCGIFCONF ioctl.
A: A slight refinement of the commands version that uses the IP command, and returns IPv4 and IPv6 addresses:
import commands,re,socket
#A generator that returns stripped lines of output from "ip address show"
iplines=(line.strip() for line in commands.getoutput("ip address show").split('\n'))
#Turn that into a list of IPv4 and IPv6 address/mask strings
addresses1=reduce(lambda a,v:a+v,(re.findall(r"inet ([\d.]+/\d+)",line)+re.findall(r"inet6 ([\:\da-f]+/\d+)",line) for line in iplines))
#addresses1 now looks like ['127.0.0.1/8', '::1/128', '10.160.114.60/23', 'fe80::1031:3fff:fe00:6dce/64']
#Get a list of IPv4 addresses as (IPstring,subnetsize) tuples
ipv4s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if '.' in addr)]
#ipv4s now looks like [('127.0.0.1', 8), ('10.160.114.60', 23)]
#Get IPv6 addresses
ipv6s=[(ip,int(subnet)) for ip,subnet in (addr.split('/') for addr in addresses1 if ':' in addr)]
A: Well you can use the command "ip route" on GNU/Linux to know your current IP address.
This shows the IP given to the interface by the DHCP server running on the router/modem. Usually "192.168.1.1/24" is the IP for local network where "24" means the range of posible IP addresses given by the DHCP server within the mask range.
Here's an example: Note that PyNotify is just an addition to get my point straight and is not required at all
#! /usr/bin/env python
import sys , pynotify
if sys.version_info[1] != 7:
raise RuntimeError('Python 2.7 And Above Only')
from subprocess import check_output # Available on Python 2.7+ | N/A
IP = check_output(['ip', 'route'])
Split_Result = IP.split()
# print Split_Result[2] # Remove "#" to enable
pynotify.init("image")
notify = pynotify.Notification("Ip", "Server Running At:" + Split_Result[2] , "/home/User/wireless.png")
notify.show()
The advantage of this is that you don't need to specify the network interface. That's pretty useful when running a socket server
You can install PyNotify using easy_install or even Pip:
easy_install py-notify
or
pip install py-notify
or within python script/interpreter
from pip import main
main(['install', 'py-notify'])
A: netifaces is available via pip and easy_install. (I know, it's not in base, but it could be worth the install.)
netifaces does have some oddities across platforms:
*
*The localhost/loop-back interface may not always be included (Cygwin).
*Addresses are listed per-protocol (e.g., IPv4, IPv6) and protocols are listed per-interface. On some systems (Linux) each protocol-interface pair has its own associated interface (using the interface_name:n notation) while on other systems (Windows) a single interface will have a list of addresses for each protocol. In both cases there is a protocol list, but it may contain only a single element.
Here's some netifaces code to play with:
import netifaces
PROTO = netifaces.AF_INET # We want only IPv4, for now at least
# Get list of network interfaces
# Note: Can't filter for 'lo' here because Windows lacks it.
ifaces = netifaces.interfaces()
# Get all addresses (of all kinds) for each interface
if_addrs = [netifaces.ifaddresses(iface) for iface in ifaces]
# Filter for the desired address type
if_inet_addrs = [addr[PROTO] for addr in if_addrs if PROTO in addr]
iface_addrs = [s['addr'] for a in if_inet_addrs for s in a if 'addr' in s]
# Can filter for '127.0.0.1' here.
The above code doesn't map an address back to its interface name (useful for generating ebtables/iptables rules on the fly). So here's a version that keeps the above information with the interface name in a tuple:
import netifaces
PROTO = netifaces.AF_INET # We want only IPv4, for now at least
# Get list of network interfaces
ifaces = netifaces.interfaces()
# Get addresses for each interface
if_addrs = [(netifaces.ifaddresses(iface), iface) for iface in ifaces]
# Filter for only IPv4 addresses
if_inet_addrs = [(tup[0][PROTO], tup[1]) for tup in if_addrs if PROTO in tup[0]]
iface_addrs = [(s['addr'], tup[1]) for tup in if_inet_addrs for s in tup[0] if 'addr' in s]
And, no, I'm not in love with list comprehensions. It's just the way my brain works these days.
The following snippet will print it all out:
from __future__ import print_function # For 2.x folks
from pprint import pprint as pp
print('\nifaces = ', end='')
pp(ifaces)
print('\nif_addrs = ', end='')
pp(if_addrs)
print('\nif_inet_addrs = ', end='')
pp(if_inet_addrs)
print('\niface_addrs = ', end='')
pp(iface_addrs)
Enjoy!
A: A Python 3.4 version utilizing the newly introduced asyncio package.
async def get_local_ip():
loop = asyncio.get_event_loop()
transport, protocol = await loop.create_datagram_endpoint(
asyncio.DatagramProtocol,
remote_addr=('8.8.8.8', 80))
result = transport.get_extra_info('sockname')[0]
transport.close()
return result
This is based on UnkwnTech's excellent answer.
A: To get the ip address you can use a shell command directly in python:
import socket, subprocess
def get_ip_and_hostname():
hostname = socket.gethostname()
shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'"
proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
ip_list = out.split('\n')
ip = ip_list[0]
for _ip in ip_list:
try:
if _ip != "127.0.0.1" and _ip.split(".")[3] != "1":
ip = _ip
except:
pass
return ip, hostname
ip_addr, hostname = get_ip_and_hostname()
A: import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
print(ip)
This will return you the IP address in the Ubuntu system as well as MacOS. The output will be the system IP address as like my IP: 192.168.1.10.
A: For a list of IP addresses on *nix systems,
import subprocess
co = subprocess.Popen(['ifconfig'], stdout = subprocess.PIPE)
ifconfig = co.stdout.read()
ip_regex = re.compile('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-4]|2[0-5][0-9]|[01]?[0-9][0-9]?))')
[match[0] for match in ip_regex.findall(ifconfig, re.MULTILINE)]
Though it's a bit late for this answer, I thought someone else may find it useful :-)
PS : It'll return Broadcast addresses and Netmask as well.
A: Note: This is not using the standard library, but quite simple.
$ pip install pif
from pif import get_public_ip
get_public_ip()
A: im using following module:
#!/usr/bin/python
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
# Python 2.7: remove the second argument for the bytes call
)[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break;
except IOError:
pass
return ip
Tested with windows and linux (and doesnt require additional modules for those)
intended for use on systems which are in a single IPv4 based LAN.
The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by Alexander.
In such cases, you need to manually replace the list with the interface names on your system, or use another solution like netifaces.
A: [Windows only] If you don't want to use external packages and don't want to rely on outside Internet servers, this might help. It's a code sample that I found on Google Code Search and modified to return required information:
def getIPAddresses():
from ctypes import Structure, windll, sizeof
from ctypes import POINTER, byref
from ctypes import c_ulong, c_uint, c_ubyte, c_char
MAX_ADAPTER_DESCRIPTION_LENGTH = 128
MAX_ADAPTER_NAME_LENGTH = 256
MAX_ADAPTER_ADDRESS_LENGTH = 8
class IP_ADDR_STRING(Structure):
pass
LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
IP_ADDR_STRING._fields_ = [
("next", LP_IP_ADDR_STRING),
("ipAddress", c_char * 16),
("ipMask", c_char * 16),
("context", c_ulong)]
class IP_ADAPTER_INFO (Structure):
pass
LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
IP_ADAPTER_INFO._fields_ = [
("next", LP_IP_ADAPTER_INFO),
("comboIndex", c_ulong),
("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
("addressLength", c_uint),
("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
("index", c_ulong),
("type", c_uint),
("dhcpEnabled", c_uint),
("currentIpAddress", LP_IP_ADDR_STRING),
("ipAddressList", IP_ADDR_STRING),
("gatewayList", IP_ADDR_STRING),
("dhcpServer", IP_ADDR_STRING),
("haveWins", c_uint),
("primaryWinsServer", IP_ADDR_STRING),
("secondaryWinsServer", IP_ADDR_STRING),
("leaseObtained", c_ulong),
("leaseExpires", c_ulong)]
GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
GetAdaptersInfo.restype = c_ulong
GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
adapterList = (IP_ADAPTER_INFO * 10)()
buflen = c_ulong(sizeof(adapterList))
rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
if rc == 0:
for a in adapterList:
adNode = a.ipAddressList
while True:
ipAddr = adNode.ipAddress
if ipAddr:
yield ipAddr
adNode = adNode.next
if not adNode:
break
Usage:
>>> for addr in getIPAddresses():
>>> print addr
192.168.0.100
10.5.9.207
As it relies on windll, this will work only on Windows.
A: I use this on my ubuntu machines:
import commands
commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
This doesn't work.
A: Variation on ninjagecko's answer. This should work on any LAN that allows UDP broadcast and doesn't require access to an address on the LAN or internet.
import socket
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect(('<broadcast>', 0))
return s.getsockname()[0]
print (getNetworkIp())
A: I had to solve the problem "Figure out if an IP address is local or not", and my first thought was to build a list of IPs that were local and then match against it. This is what led me to this question. However, I later realized there is a more straightfoward way to do it: Try to bind on that IP and see if it works.
_local_ip_cache = []
_nonlocal_ip_cache = []
def ip_islocal(ip):
if ip in _local_ip_cache:
return True
if ip in _nonlocal_ip_cache:
return False
s = socket.socket()
try:
try:
s.bind((ip, 0))
except socket.error, e:
if e.args[0] == errno.EADDRNOTAVAIL:
_nonlocal_ip_cache.append(ip)
return False
else:
raise
finally:
s.close()
_local_ip_cache.append(ip)
return True
I know this doesn't answer the question directly, but this should be helpful to anyone trying to solve the related question and who was following the same train of thought. This has the advantage of being a cross-platform solution (I think).
A: On Debian (tested) and I suspect most Linux's..
import commands
RetMyIP = commands.getoutput("hostname -I")
On MS Windows (tested)
import socket
socket.gethostbyname(socket.gethostname())
A: A version I do not believe that has been posted yet.
I tested with python 2.7 on Ubuntu 12.04.
Found this solution at : http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
Example Result:
>>> get_ip_address('eth0')
'38.113.228.130'
A: As an alias called myip:
alias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"
*
*Works correctly with Python 2.x, Python 3.x, modern and old Linux distros, OSX/macOS and Windows for finding the current IPv4 address.
*Will not return the correct result for machines with multiple IP addresses, IPv6, no configured IP address or no internet access.
*Reportedly, this does not work on the latest releases of macOS.
NOTE: If you intend to use something like this within a Python program, the proper way is to make use of a Python module that has IPv6 support.
Same as above, but only the Python code:
import socket
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
*
*This will throw an exception if no IP address is configured.
Version that will also work on LANs without an internet connection:
import socket
print((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0])
(thanks @ccpizza)
Background:
Using socket.gethostbyname(socket.gethostname()) did not work here, because one of the computers I was on had an /etc/hosts with duplicate entries and references to itself. socket.gethostbyname() only returns the last entry in /etc/hosts.
This was my initial attempt, which weeds out all addresses starting with "127.":
import socket
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
This works with Python 2 and 3, on Linux and Windows, but does not deal with several network devices or IPv6. However, it stopped working on recent Linux distros, so I tried this alternative technique instead. It tries to connect to the Google DNS server at 8.8.8.8 at port 53:
import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])
Then I combined the two above techniques into a one-liner that should work everywhere, and created the myip alias and Python snippet at the top of this answer.
With the increasing popularity of IPv6, and for servers with multiple network interfaces, using a third-party Python module for finding the IP address is probably both more robust and reliable than any of the methods listed here.
A: For linux, you can just use check_output of the hostname -I system command like so:
from subprocess import check_output
check_output(['hostname', '-I'])
A: You can use the netifaces module. Just type:
pip install netifaces
in your command shell and it will install itself on default Python installation.
Then you can use it like this:
from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
print '%s: %s' % (ifaceName, ', '.join(addresses))
On my computer it printed:
{45639BDC-1050-46E0-9BE9-075C30DE1FBC}: 192.168.0.100
{D43A468B-F3AE-4BF9-9391-4863A4500583}: 10.5.9.207
Author of this module claims it should work on Windows, UNIX and Mac OS X.
A: This is a variant of UnkwnTech's answer -- it provides a get_local_addr() function, which returns the primary LAN ip address of the host. I'm posting it because this adds a number of things: ipv6 support, error handling, ignoring localhost/linklocal addrs, and uses a TESTNET addr (rfc5737) to connect to.
# imports
import errno
import socket
import logging
# localhost prefixes
_local_networks = ("127.", "0:0:0:0:0:0:0:1")
# ignore these prefixes -- localhost, unspecified, and link-local
_ignored_networks = _local_networks + ("0.", "0:0:0:0:0:0:0:0", "169.254.", "fe80:")
def detect_family(addr):
if "." in addr:
assert ":" not in addr
return socket.AF_INET
elif ":" in addr:
return socket.AF_INET6
else:
raise ValueError("invalid ipv4/6 address: %r" % addr)
def expand_addr(addr):
"""convert address into canonical expanded form --
no leading zeroes in groups, and for ipv6: lowercase hex, no collapsed groups.
"""
family = detect_family(addr)
addr = socket.inet_ntop(family, socket.inet_pton(family, addr))
if "::" in addr:
count = 8-addr.count(":")
addr = addr.replace("::", (":0" * count) + ":")
if addr.startswith(":"):
addr = "0" + addr
return addr
def _get_local_addr(family, remote):
try:
s = socket.socket(family, socket.SOCK_DGRAM)
try:
s.connect((remote, 9))
return s.getsockname()[0]
finally:
s.close()
except socket.error:
# log.info("trapped error connecting to %r via %r", remote, family, exc_info=True)
return None
def get_local_addr(remote=None, ipv6=True):
"""get LAN address of host
:param remote:
return LAN address that host would use to access that specific remote address.
by default, returns address it would use to access the public internet.
:param ipv6:
by default, attempts to find an ipv6 address first.
if set to False, only checks ipv4.
:returns:
primary LAN address for host, or ``None`` if couldn't be determined.
"""
if remote:
family = detect_family(remote)
local = _get_local_addr(family, remote)
if not local:
return None
if family == socket.AF_INET6:
# expand zero groups so the startswith() test works.
local = expand_addr(local)
if local.startswith(_local_networks):
# border case where remote addr belongs to host
return local
else:
# NOTE: the two addresses used here are TESTNET addresses,
# which should never exist in the real world.
if ipv6:
local = _get_local_addr(socket.AF_INET6, "2001:db8::1234")
# expand zero groups so the startswith() test works.
if local:
local = expand_addr(local)
else:
local = None
if not local:
local = _get_local_addr(socket.AF_INET, "192.0.2.123")
if not local:
return None
if local.startswith(_ignored_networks):
return None
return local
A: Ok so this is Windows specific, and requires the installation of the python WMI module, but it seems much less hackish than constantly trying to call an external server. It's just another option, as there are already many good ones, but it might be a good fit for your project.
Import WMI
def getlocalip():
local = wmi.WMI()
for interface in local.Win32_NetworkAdapterConfiguration(IPEnabled=1):
for ip_address in interface.IPAddress:
if ip_address != '0.0.0.0':
localip = ip_address
return localip
>>>getlocalip()
u'xxx.xxx.xxx.xxx'
>>>
By the way, WMI is very powerful... if you are doing any remote admin of window machines you should definitely check out what it can do.
A: import socket
socket.gethostbyname(socket.getfqdn())
A: This isn't very Pythonic, but it works reliably on Windows.
def getWinIP(version = 'IPv4'):
import subprocess
if version not in ['IPv4', 'IPv6']:
print 'error - protocol version must be "IPv4" or "IPv6"'
return None
ipconfig = subprocess.check_output('ipconfig')
my_ip = []
for line in ipconfig.split('\n'):
if 'Address' in line and version in line:
my_ip.append(line.split(' : ')[1].strip())
return my_ip
print getWinIP()
Yeah, it's a hack, but at times I don't feel like second-guessing an operating system, and just go ahead and use what's built-in and works.
A: from netifaces import interfaces, ifaddresses, AF_INET
iplist = [ifaddresses(face)[AF_INET][0]["addr"] for face in interfaces() if AF_INET in ifaddresses(face)]
print(iplist)
['10.8.0.2', '192.168.1.10', '127.0.0.1']
A: A machine can have multiple network interfaces (including the local loopback 127.0.0.1) you mentioned. As far as the OS is concerned, it's also a "real IP address".
If you want to track all of interfaces, have a look at the following Python package, see: http://alastairs-place.net/netifaces/
I think you can avoid having gethostbyname return 127.0.0.1 if you ommit the loopback entry from your hosts file. (to be verified).
A: Yet another variant to previous answers, can be saved to an executable script named my-ip-to:
#!/usr/bin/env python
import sys, socket
if len(sys.argv) > 1:
for remote_host in sys.argv[1:]:
# determine local host ip by outgoing test to another host
# use port 9 (discard protocol - RFC 863) over UDP4
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((remote_host, 9))
my_ip = s.getsockname()[0]
print(my_ip, flush=True)
else:
import platform
my_name = platform.node()
my_ip = socket.gethostbyname(my_name)
print(my_ip)
it takes any number of remote hosts, and print out local ips to reach them one by one:
$ my-ip-to z.cn g.cn localhost
192.168.11.102
192.168.11.102
127.0.0.1
$
And print best-bet when no arg is given.
$ my-ip-to
192.168.11.102
A: For a linux env, read the /proc/net/tcp, the second (localaddress) and third (remoteaddress) will give the IPs at hexa format.
Tip: If second column is zeroed (00000000:0000) so its a Listen Port :)
https://github.com/romol0s/python/blob/master/general/functions/getTcpListenIpsByPort.py
https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt
A: Windows solution, Take it or leave it.
gets only the self ip, on the current active wlan[wireless LAN] ie the computer's ip on the (wifi router or network switch).
note: its not the public ip of the device and does not involve any external requests or packages or public apis.
The core idea is to parse the output of shell command: ipconfig, or ifconfig on linux. we are using subprocess to acquire the output.
def wlan_ip():
import subprocess
result=subprocess.run('ipconfig',stdout=subprocess.PIPE,text=True).stdout.lower()
scan=0
for i in result.split('\n'):
if 'wireless' in i: #use "wireless" or wireless adapters and "ethernet" for wired connections
scan=1
if scan:
if 'ipv4' in i:
return i.split(':')[1].strip()
print(wlan_ip())
this is what happens after CMD:'ipconfig' :
we get this output, we captured it in python using subprocess output.
C:\Users\dell>ipconfig
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::f485:4a6a:e7d5:1b1c%4
IPv4 Address. . . . . . . . . . . : 192.168.0.131
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.0.1
and we parsed the string in python, in a manner that selects the wireless adapter's ip on current network.
A: You can do this easily on modern *NIX systems that have the iproute2 utility by calling it via subprocess.run() as you can output in JSON with the -j switch and then use the json.loads() module and method to convert that to a python data structure. The following code displays the first non loopback IP address.
import subprocess
import json
ip = json.loads(subprocess.run('ip -j a'.split(),capture_output=True).stdout.decode())[1]['addr_info'][0]['local']
print(ip)
Alternativly if you had multiple IP's and wanted to find the IP that would be used to connect to a specific destination you could use ip -j route get 8.8.8.8 like this:
import subprocess
import json
ip = json.loads(subprocess.run('ip -j route get 8.8.8.8'.split(),capture_output=True).stdout.decode())[0]['prefsrc']
print(ip)
If your looking for all IP addresses you can iterate through the list of dictionaries returned by ip -j a
import subprocess
import json
list_of_dicts = json.loads(subprocess.run('ip -j a'.split(),capture_output=True).stdout.decode())
for interface in list_of_dicts:
try:print(f"Interface: {interface['ifname']:10} IP: {interface['addr_info'][0]['local']}")
except:pass
A: Here are two solutions, I tried to keep them very simple, and to explain each step.
TLDR;
First solution:
import socket, os
hostname = os.uname()[1]
print(socket.gethostbyname_ex(hostname)[2])
Second solution:
import socket
hostname = socket.gethostname()
print(socket.gethostbyname_ex(hostname)[2])
On my machine, both codes return a list containing the IP addresses:
['127.0.1.1', '192.168.1.47']
Detailed explanation:
First, get the hostname of the local machine by using uname function from the os module:
import os
hostname = os.uname()[1]
print(hostname) # Just to display an output
Note that this can also be done by calling the gethostname function from the socket module:
import socket
hostname = socket.gethostname()
print(hostname) # Just to display an output
Now, when passing this hostname to the gethostbyname_ex function from the socket module, it returns a tuple, the third part of that tuple is a list of the IP addresses:
addresses = socket.gethostbyname_ex(hostname)[2]
print(addresses) # Just to display an output
Note that this was largely inspired by a combination of answers above; I just tried to simplify things and make them as clear as possible.
A: I settled for using the service and/or API of ipfy: https://www.ipify.org.
#!/usr/bin/env python3
from urllib.request import urlopen
def public_ip():
data = urlopen('https://api.ipify.org').read()
return str(data, encoding='utf-8')
print(public_ip())
The response can also be obtained in JSON and JSONP formats.
There's an ipify Python library on Github.
A: import socket
print(socket.gethostbyname(socket.getfqdn()))
A: @fatal_error solution should be the accepted answer! this is an implementation of his solution in nodejs in case people need it:
const dgram = require('dgram');
async function get_local_ip() {
const s = new dgram.createSocket('udp4');
return new Promise((resolve, reject) => {
try {
s.connect(1, '8.8.8.8', function () {
const ip = s.address();
s.close();
resolve(ip.address)
});
} catch (e) {
console.error(e);
s.close();
reject(e);
}
})
}
A: Simple yet sweet!
def getip():
import socket
hostname= socket.gethostname()
ip=socket.gethostbyname(hostname)
return(ip)
A: This is very similar to previously posted answers, but I could not find any with this usage of calls. This is what I use for ipv4. For ipv6 change the '.' in to ':' in
import socket
print next(i[4][0] for i in socket.getaddrinfo(
socket.gethostname(), 80) if '127.' not in i[4][0] and '.' in i[4][0]);"
A: pyroute2 is a great library that can be used to obtain not just ip addresses but also gateway information and other useful information.
The following code can obtain the ipv4 address of any interface.
from pyroute2 import IPRoute
ip = IPRoute()
def get_ipv4_address(intf):
return dict(ip.get_addr(label=intf)[0]['attrs'])['IFA_LOCAL']
print(get_ipv4_address('eth0'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "684"
} |
Q: Unix shell events? Is there any way so that i can echo password when asked for in unix shell without use of external binaries ? Something like simple function triggered when password prompt is displayed
A: Are you aware of Expect?
Perhaps this falls in the "external binaries" category, but if it does, then your question needs clarification.
A: Short answer: no.
Slightly longer answer: the usual shells, sh, ksh, csh, tcsh, bash do not have any hooks for you to hang actions on (OK, so bash2 has context sensitive tab-completion).
On the other hand. The shell is just a program. You can replace it. If you can really say what you want to do you can hack and existing shell or write a new one to get the desired behavior...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server 2005 Computed Column Result From Aggregate Of Another Table Field's Value Sorry for the long question title.
I guess I'm on to a loser on this one but on the off chance.
Is it possible to make the calculation of a calculated field in a table the result of an aggregate function applied to a field in another table.
i.e.
You have a table called 'mug', this has a child called 'color' (which makes my UK head hurt but the vendor is from the US, what you going to do?) and this, in turn, has a child called 'size'. Each table has a field called sold.
The size.sold increments by 1 for every mug of a particular colour and size sold.
You want color.sold to be an aggregate of SUM size.sold WHERE size.colorid = color.colorid
You want mug.sold to be an aggregate of SUM color.sold WHERE color.mugid = mug.mugid
Is there anyway to make mug.sold and color.sold just work themselves out or am I going to have to go mucking about with triggers?
A: you can't have a computed column directly reference a different table, but you can have it reference a user defined function. here's a link to a example of implementing a solution like this.
http://www.sqlservercentral.com/articles/User-Defined+functions/complexcomputedcolumns/2397/
A: No, it is not possible to do this. A computed column can only be derived from the values of other fields on the same row. To calculate an aggregate off another table you need to create a view.
If your application needs to show the statistics ask the following questions:
*
*Is it really necessary to show this in real time? If so, why? If it is really necesary to do this, then you would have to use triggers to update a table. This links to a short wikipedia article on denormalisation. Triggers will affect write performance on table updates and relies on the triggers being active.
*If it is only necessary for reporting purposes, you could do the calculation in a view or a report.
*If it is necessary to support frequent ad-hoc reports you may be into the realms of a data mart and overnight ETL process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Does NetworkStream.DataAvailable see buffered data? Does NetworkStream.DataAvailable know whether the sender's send buffer is empty? Or does it simply indicate whether the receiver's read buffer has data? My assumption is the latter...
Specifically, for some socket work involving an ongoing conversation, I currently use a length-prefix so the the receiver knows exactly how much data is in the current batch; however, I've been sent a .patch suggesting I use NetworkStream.DataAvailable instead. My concern is that this will just tell me what the receiver has got - not what the sender originally sent - but I'm not a sockets expert.
Am I wrong? Or is length-prefix the way to go?
(note I can't simply Read() until the stream is closed, since multiple batches are sent on the same connection, and it is vital that I treat each batch as separate; if I read too much in one batch (even if it gets buffered and discarded) then the conversation will break).
A: One side of a connection is not going to know whether the other side's send buffer is empty.
DataAvailable only indicates whether there is incoming data to be read. You could use that prior to Read(), but it alone doesn't give you the information you want. It doesn't tell you the beginning and ending of each batch.
I've coded back-and-forth conversation before, and I used length-prefixes in the data. What I did was write helper functions that read an exact number of bytes (chunks at a time) and no more.
The only alternative to length-of-batch values in the stream is some way of examining the incoming data and recognizing the beginnings and endings of batches.
A: If you are needing to know when the receiver has received all of the data for a particular message then you definitely need to length prefix.
I typically define a struct similar to this that goes out at the front of any binary messages i send.
struct Header
{
int packetIdentifier;
int protocolVersion;
int messageType;
int payloadSize;
}
The identifier lets you determine if you have a valid message of your protocol type. The version lets you revision your protocol. The message type is the type of message (ie: CommsOnline). The payload size is the size of the body of the message.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using boost in embedded system with memory limitation We are using c++ to develop an application that runs in Windows CE 4 on an embedded system.
One of our constraint is that all the memory used by the application shall be allocated during startup only. We wrote a lot of containers and algorithms that are using only preallocated memory instead of allocating new one.
Do you think it is possible for us to use the boost libraries instead of our own containers in these conditions?
Any comments and/or advice are welcomed!
Thanks a lot,
Nic
A: You could write your own allocator for the container, which allocates from a fixed size static buffer. Depending on the usage patterns of the container the allocator could be as simple as incrementing a pointer (e.g. when you only insert stuff into the container once at app startup, and don't continuously add/remove elements.)
A: Replacing your containers with Boost containers is NOT a good idea. The work to make appropriate custom allocators wouldn't be that bad, but you'd be violating the spirit of your 'allocate at startup' rule. The idea behind this rule (in my experience) is generally to make sure that you don't have to deal with out of memory type situations at run-time. The idea is to make sure that you have all the memory you could possibly need RIGHT AT THE START, so that there's no possibility of any part of the system coming up short of memory later on.
If you used the Boost containers with a custom allocator, you'd suddenly have to deal with the possibility that the pool the container is allocating from could go empty, thus eliminating the purpose of the 'allocate at startup' rule.
In the situation of a limited memory device, I would avoid any kind of container more complex than a statically allocated array.
A: We use boost for embedded systems. With boost you can pick and choose what you use. We use smart_ptr and boost::bind in all of our projects. We write software for cheap cell phones.
And if Windows CE can run on your hardware I would expect that parts of boost would be applicable.
There are parts of boost that have no allocation and you might find them useful.
I would pick and choose based on your requirements.
Like anything that you use, you need to know the costs.
A: Boost is a set of libraries. Some of them are focussed on template metaprogramming. Those don't even use any memory at runtime. But your question seems to be about replacing your containers. I'd doubt that is possible except using custom allocators. But even then, it's most likely you would be using plain STL containers and not boost. Boost only provides the TR1 containers, for those compilers that do not yet include TR1.
A: Do not use Boost.
It is a big library and your basic memory allocation requirements are very different from those of the libraries designers.
Even if you can get a current version of Boost to work according to your requirements with custom allocators it may break with a new version of Boost.
Feel free to look at the Boost source code though for some useful ideas but use your own implementation for what you need.
A: I'm looking into this right now — I would like to use circular buffers, lock-free containers, and asynchronous I/O, and instead of allocating dynamic memory, I'd prefer to use memory pools.
The biggest problem I've seen so far is that shared_ptr is used in a lot of places, with no easy way to replace it with intrusive_ptr. Since shared_ptr allocates dynamic memory to keep track of the reference count, I can't use it in an embedded system.
Fixing this looks doable, but a lot of work — I have to expand the template specification of any class that contains a shared_ptr so that the specific type of shared-pointer can be changed to intrusive_ptr if desired. So now I have to consider how much work that'll be, versus how much work it'll be to write my own version of the Boost features I need. Not a pleasant place to be.
I hope someone points out why I'm wrong about this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Reuse Edit Control as Command Window This is a GUI application (actually MFC). I need a command window with the ability to display a prompt like such:
Name of favorite porn star:
The user should be able to enter text after the prompt like such:
Name of favorite porn star: Raven Riley
But I need to prevent the user from moving the cursor into the prompt area. Users should also be prevented from backspacing into the prompt in order to prevent the following:
Rrraven Rrrileeey Ruuuulez!!! Name of favorite porn star:
Also need to control text selection and so on. And finally, I should have no problem retrieving only the text the user entered (minus prompt text).
Will it be better to create my own window class from scratch (i.e inherit from CWnd) or should I reuse the Windows EDIT control (i.e. inherit from CEdit)?
A similar command window can be seen in AutoCAD and Visual Studio (in debug mode).
A: I think you'd be better off creating a subclass of CEdit and limiting filtering key-presses. I suppose the hard part is not letting the user move the caret to the prompt area, but you can probably write some code to make sure the caret always get sent back to where it belongs (the input part).
Anyway, if you really, really want to implement your own control (it's not that difficult after all) I recommend you read Jacob Navia's "technical documentation" on how he built the LCC compiler and environment. Actually, it seems the docs are not online anymore, but I'm sure you can get them through his e-mail (jacob@jacob.remcomp.fr).
Edit: I liked your previous example better. Keep it classy, LOL :)
A: I had a very similar requirement and did exactly what davidg suggested; subclassed a edit control and filtered key presses. This was actually using Qt not MFC but the principle will be exactly the same.
You need to remember to filter keys such as home as well as left and backspace. I just checked to see if the move would move the caret into the prompt and if it did ignored the keypress.
Another thing to watch for is pasting multiline text, you will have to choose whether to just paste the first line or all lines, adding the prompt on all lines after the first. When subclassing the control you get lots of behaviour which won't work exactly as you want it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Finding a public facing IP address in Python? How can I find the public facing IP for my net work in Python?
A: whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.
import urllib
ip = urllib.urlopen('http://whatismyip.org').read()
But yeah, it's impossible to do it easily without relying on something outside the network itself.
A: import requests
r = requests.get(r'http://jsonip.com')
# r = requests.get(r'https://ifconfig.co/json')
ip= r.json()['ip']
print('Your IP is {}'.format(ip))
Reference
A: If you don't mind expletives then try:
http://wtfismyip.com/json
Bind it up in the usual urllib stuff as others have shown.
There's also:
http://www.networksecuritytoolkit.org/nst/tools/ip.php
A: import urllib2
text = urllib2.urlopen('http://www.whatismyip.org').read()
urlRE=re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',text)
urlRE
['146.148.123.123']
Try putting whatever 'findmyipsite' you can find into a list and iterating through them for comparison. This one seems to work well.
A: This will fetch your remote IP address
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
If you don't want to rely on someone else, then just upload something like this PHP script:
<?php echo $_SERVER['REMOTE_ADDR']; ?>
and change the URL in the Python or if you prefer ASP:
<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
Note: I don't know ASP, but I figured it might be useful to have here so I googled.
A: https://api.ipify.org/?format=json is pretty straight forward
can be parsed by just running requests.get("https://api.ipify.org/?format=json").json()['ip']
A: This is simple as
>>> import urllib
>>> urllib.urlopen('http://icanhazip.com/').read().strip('\n')
'xx.xx.xx.xx'
A: You can also use DNS which in some cases may be more reliable than http methods:
#!/usr/bin/env python3
# pip install --user dnspython
import dns.resolver
resolver1_opendns_ip = False
resolver = dns.resolver.Resolver()
opendns_result = resolver.resolve("resolver1.opendns.com", "A")
for record in opendns_result:
resolver1_opendns_ip = record.to_text()
if resolver1_opendns_ip:
resolver.nameservers = [resolver1_opendns_ip]
myip_result = resolver.resolve("myip.opendns.com", "A")
for record in myip_result:
print(f"Your external ip is {record.to_text()}")
This is the python equivalent of dig +short -4 myip.opendns.com @resolver1.opendns.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: What to put in the IF block and what to put in the ELSE block? This is a minor style question, but every bit of readability you add to your code counts.
So if you've got:
if (condition) then
{
// do stuff
}
else
{
// do other stuff
}
How do you decide if it's better like that, or like this:
if (!condition) then
{
// do other stuff
{
else
{
// do stuff
}
My heuristics are:
*
*Keep the condition positive (less
mental calculation when reading it)
*Put the most common path into the
first block
A: Two (contradictory) textbook quotes:
Put the shortest clause of an if/else
on top
--Allen Holub, "Enough Rope to Shoot Yourself in the Foot", p52
Put the normal case after the if rather than after the else
--Steve McConnell, "Code Complete, 2nd ed.", p356
A: I prefer the first one. The condition should be as simple as possible and it should be fairly obvious which is simpler out of condition and !condition
A: It depends on your flow. For many functions, I'll use preconditions:
bool MyFunc(variable) {
if (variable != something_i_want)
return false;
// a large block of code
// ...
return true;
}
If I need to do something each case, I'll use an if (positive_clause) {} else {} format.
A: If the code is to check for an error condition, I prefer to put that code first, and the "successful" code second; conceptually, this keeps a function call and its error-checking code together, which makes sense to me because they are related. For example:
if (!some_function_that_could_fail())
{
// Error handling code
}
else
{
// Success code
}
A: I agree with Oli on using a positive if clause when possible.
Just please never do this:
if (somePositiveCondition)
else {
//stuff
}
I used to see this a lot at one place I worked and used to wonder if one of the coders didn't understand how not works...
A: When I am looking at data validation, I try to make my conditions "white listing" - that is, I test for what I will accept:
if DataIsGood() then
DoMyNormalStuff
else
TakeEvasiveAction
Rather than the other way around, which tends to degenerate into:
if SomeErrorTest then
TakeSomeEvasiveAction
else if SomeOtherErrorCondition then
CorrectMoreStupidUserProblems
else if YetAnotherErrorThatNoOneThoughtOf then
DoMoreErrorHandling
else
DoMyNormalStuff
A: I know this isn't exactly what you're looking for, but ... A lot of developers use a "guard clause", that is, a negative "if" statement that breaks out of the method as soon as possible. At that point, there is no "else" really.
Example:
if (blah == false)
{
return; // perhaps with a message
}
// do rest of code here...
There are some hard-core c/c++/assembly guys out there that will tell you that you're destroying your CPU!!! (in many cases, processors favor the "true" statement and try to "prefetch" the next thing to do... so theoretically any "false" condition will flush the pipe and will go microseconds slower).
In my opinion, we are at the point where "better" (more understandable) code wins out over microseconds of CPU time.
A: I think that for a single variable the not operator is simple enough and naming issues start being more relevant.
Never name a variable not_X, if in need use a thesaurus and find an opposite. I've seen plenty of awful code like
if (not_dead) {
} else {
}
instead of the obvious
if (alive) {
} else {
}
Then you can sanely use (very readable, no need to invert the code blocks)
if (!alive) {
} else {
}
If we're talking about more variables I think the best rule is to simplify the condition. After a while projects tend to get conditions like:
if (dead || (!dead && sleeping)) {
} else {
}
Which translates to
if (dead || sleeping) {
} else {
}
Always pay attention to what conditions look like and how to simplify them.
A: Software is knowledge capture. You're encoding someone's knowledge of how to do something.
The software should fit what's "natural" for the problem. When in doubt, ask someone else and see what people actually say and do.
What about the situation where the "common" case is do nothing? What then
if( common ) {
// pass
}
else {
// great big block of exception-handling folderol
}
Or do you do this?
if( ! common ) {
// great big block of except-handling folderol
}
The "always positive" rule isn't really what you want first. You want to look at rules more like the following.
*
*Always natural -- it should read like English (or whatever the common language in your organization is.)
*Where possible, common cases first -- so they appear common.
*Where possible use positive logic; negative logic can be used where it's commonly said that way or where the common case is a do-nothing.
A: If one of the two paths is very short (1 to 10 lines or so) and the other is much longer, I follow the Holub rule mentioned here and put the shorter piece of code in the if. That makes it easier to see the if/else flow on one screen when reviewing the code.
If that is not possible, then I structure to make the condition as simple as possible.
A: I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.
if (condition)
return;
DoSomething();
I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.
A: For me it depends on the condition, for example:
if (!PreserveData.Checked)
{ resetfields();}
I tend to talk to my self with what I want the logic to be and code it to the little voice in my head.
A: You can usually make the condition positive without switching around the if / else blocks.
Change
if (!widget.enabled()) {
// more common
} else {
// less common
}
to
if (widget.disabled()) {
// more common
} else {
// less common
}
A: Intel Pentium branch prediction pre-fetches instructions for the "if" case. If it instead follows the "else" branch: it has the flush the instruction pipeline, causing a stall.
If you care a lot about performance: put the most likely outcome in the 'if' clause.
Personally i write it as
if (expected)
{
//expected path
}
else
{
//fallback other odd case
}
A: If you have both true and false conditions then I'd opt for a positive conditional - This reduces confusion and in general I believe makes your code easier to read.
On the other hand, if you're using a language such as Perl, and particularly if your false condition is either an error condition or the most common condition, you can use the 'unless' structure, which executes the code block unless the condition is true (i.e. the opposite of if):
unless ($foo) {
$bar;
}
A: First of all, let's put aside situations when it is better to avoid using "else" in the first place (I hope everyone agrees that such situations do exist and determining such cases probably should be a separate topic).
So, let's assume that there must be an "else" clause.
I think that readability/comprehensibility imposes at least three key requirements or rules, which unfortunately often compete with each other:
*
*The shorter is the first block (the "if" block) the easier is it to grasp the entire "if-else" construct. When the "if" block is long enough, it becomes way too easy to overlook existence of "else" block.
*When the "if" and "else" paths are logically asymmetric (e.g. "normal processing" vs. "error processing"), in a standalone "if-else" construct it does not really matter much which path is first and which is second. However, when there are multiple "if-else" constructs in proximity to each other (including nesting), and when all those "if-else" constructs have asymmetry of the same kind - that's when it is very important to arrange those asymmetric paths consistently.
Again, it can be "if ... normal path ... else ... abnormal path" for all, or "if ... abnormal path ... else ... normal path" for all, but it should not be a mix of these two variants.
With all other conditions equal, putting the normal path first is probably more natural for most human beings (I think it's more about psychology than aesthetics :-).
*An expression that starts with a negation usually is less readable/comprehensible than an expression that doesn't.
So, we have these three competing requirements/rules, and the real question is: which of them are more important than others. For Allen Holub the rule #1 is probably the most important one. For Steve McConnell - it is the rule #2. But I don't think that you can really choose only one of these rules as a single quideline.
I bet you've already guessed my personal priorities here (from the way I ordered the rules above :-).
My reasons are simple:
*
*The rule #1 is unconditional and impossible to circumvent. If one of the blocks is so long that it runs off the screen - it must become the "else" block. (No, it is not a good idea to create a function/method mechanically just to decrease the number of lines in an "if" or "else" block! I am assuming that each block already has a logically justifiable minimum amount of lines.)
*The rule #2 involves a lot of conditions: multiple "if-else" constructs, all having asymmetry of the same kind, etc. So it just does not apply in many cases.
Also, I often observe the following interesting phenomenon: when the rule #2 does apply and when it is used properly, it actually does not conflict with the rule #1! For example, whenever I have a bunch of "if-else" statements with "normal vs. abnormal" asymmetry, all the "abnormal" paths are shorter than "normal" ones (or vice versa). I cannot explain this phenomenon, but I think that it's just a sign of good code organization. In other words, whenever I see a situation when rules #1 and #2 are in conflict, I start looking for "code smells" and more often than not I do find some; and after refactoring - tada! no more painful choosing between rule #1 and rule #2, :-)
*Finally, the rule #3 hase the smallest scope and therefore is the least critical.
Also, as mentined here by other colleagues, it is often very easy to "cheat" with this rule (for example, to write "if(disabled),,," instead of "if(!enabled)...").
I hope someone can make some sense of this opus...
A: As a general rule, if one is significantly larger than the other, I make the larger one the if block.
A: *
*put the common path first
*turn negative cheking into positive ones (!full == empty)
A: If you must have multiple exit points, put them first and make them clear:
if TerminatingCondition1 then
Exit
if TerminatingCondition2 then
Exit
Now we can progress with the usual stuff:
if NormalThing then
DoNormalThing
else
DoAbnormalThing
A: I always keep the most likely first.
In Perl I have an extra control structure to help with that. The inverse of if.
unless (alive) {
go_to_heaven;
} else {
say "MEDIC";
}
A: You should always put the most likely case first. Besides being more readable, it is faster. This also applies to switch statements.
A: I'm horrible when it comes to how I set up if statements. Basically, I set it up based on what exactly I'm looking for, which leads everything to be different.
if (userinput = null){
explodeViolently();
} else {
actually do stuff;
}
or perhaps something like
if (1+1=2) {
do stuff;
} else {
explodeViolently();
}
Which section of the if/else statement actually does things for me is a bad habit of mine.
A: I generally put the positive result (so the method) at the start so:
if(condition)
{
doSomething();
}
else
{
System.out.println("condition not true")
}
But if the condition has to be false for the method to be used, I would do this:
if(!condition)
{
doSomething();
}
else
{
System.out.println("condition true");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: A good database modeling tool? Could you guys recommend me a good db modeling tool? Mainly for SQL Server...
thanks!
A: If your employer is paying, ER Studio is fantastic. I don't know how other people can function without it. It easily makes me 50% more productive.
A: StarUML has a module that allows for the creation of Entity Relationship Diagrams. However, I've never used it for this purpose, so I don't know how good it is, but I do like StarUML for UML diagrams.
A: Funny as it is I've found:
WWW SQL Designer
to be useful in a pinch. I'm also a fan of his Instant SQL Formatter though by "instant" he means "not T-SQL" so you have to some slight hand editing of Profiler recorded statements to use his system fully.
A: I heartily recommend Sparx Enterprise Architect.
Alternatively Visio for Enterprise Architects works moderately well and you could get it together with Visual Studio.
A: ERwin Data Modeler is the best tool for Enterprise database modelling in my opinion.
I've used it a number of times and it is great.
See: http://www.ca.com/us/products/product.aspx?id=260
It is a little bit pricey, but it is worth it. You can also trial it for free.
A: I tried Navicat Data Modeler. It's the best data modeling tool I've found so far. It has a free version.
Free version can be found at: Navicat Data Modeler
A: If it is for SQL Server I like the DB Diagram from SQL Server Management Studio.
A: If you mean for drawing Entity Relationship Diagrams, then I suggest Visio. It will even build your database from the Diagram.
A: try http://www.fabforce.net/dbdesigner4/ for MySQL
A: I tend to use SQL Server Management Studio also for quickly doing stuff, but when I am doing the actual implementation or more advanced stuff I use EMS Sql Manager. It is quite a nice tool with far more advanced and more numerous features than Sql Management studio. You can think of it as MS SQL Management Studio on steroids. Takes a bit of getting used to the UI though, but still straight forward enough. And if you get their package with all their peoducts you get a ton of great utilities as well.
If its just diagramming thoguh i will use Visio.
A: I've been using for some time with great success what used to be called 'Case Studio'. It's now called 'Toad Data Modeller'..
It's pay, but quite good, worth at least a trial.
A: Personally I always liked Dia, it's ubiquitous, portable, easy to use and supports a whole bunch of other diagrams other than just ER/UML so I can use it to make diagrams for non-techies.
A: ModelRight, from http://www.modelright.com is very good for physical modeling. Excellent support for Oracle, MySQL, SQL Server, etc.
A: I used pencil and paper quite successfully to get the initial entities and relationships down. Especially good if designing with other people, you don't get distracted by the GUI interface, mousing around, getting the background gradients right, etc. Then you can translate it into Visio or Dia or a UML tool that generates both the SQL Schema and your object model...
Usually after this time constraints mean you end up in TOAD or your DB tool of choice getting the tables, indexes, foreign keys and stuff implemented in straight SQL or with their table designer tool. Changes will inevitably come up downstream so don't spend too long getting things exactly, just get the structure right.
A: You can draw ERDs using GraphViz records. That will not trak/organize your metadata, geneate your DDL or anything else for that matter - but it will give you an entity relationship diagram that you can easily edit/update.
It will handle all the layout/arrangement details of the diagram for you. It does a pretty good job of this. It is sort of a declarative diagram-drawing language. Very simple to learn. Requires nothing but a text editor to use. Many applications use its abilities behind the scenes to generate their diagrams also.
A: I second Embarcadero ERStudio. Not cheap but powerful, multiplatform and really easy to use.
A: Well, if you're using SQL Server, as I've mentioned in other posts Visio probably will work really well for you. You probably already have it or your IT shop does so the cost is negligible and it can import an existing database or if you build from scratch can export it to a designated SQL Server.
I've used it several times and have been happy with the results.
A: ModelRight is the best tool out there - especially for the money.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: HTTP response splitting I'm trying to handle this possible exploit and wondering what is the best way to do it? should i use apache's common-validator and create a list of known allowed symbols and use that?
A: From the wikipedia article:
The generic solution is to URL-encode strings before inclusion into HTTP headers such as Location or Set-Cookie.
Typical examples of sanitization include casting to integer, or aggressive regular expression replacement. It is worth noting that although this is not a PHP specific problem, the PHP interpreter contains protection against this attack since version 4.4.2 and 5.1.2.
Edit
im tied into using jsp's with java actions!
There don't appear to be any JSP-based protections for this attack vector - many descriptions on the web assume asp or php, but this link describes a fairly platform-neutral way to approach the problem (jsp used as an incidental example in it).
Basically your first step is to indentify the potentially hazardous characters (CRs, LFs, etc) and then to remove them. I'm afraid this about as robust a solution as you can hope for!
Solution
Validate input. Remove CRs and LFs (and all other hazardous characters) before embedding data into any HTTP response headers, particularly when setting cookies and redirecting. It is possible to use third party products to defend against CR/LF injection, and to test for existence of such security holes before application deployment.
A: Use PHP? ;)
According to Wikipedia and the PHP CHANGELOG, PHP's had protection against it in PHP4 since 4.4.2 and PHP5 since 5.1.2.
Only skimmed it -- but, this might help. His examples are written in JSP.
A: ok, well casting to an int is not much use when reading strings, also using regex in every action which recieves input from browser could be messy, im looking for a more robust solution
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flash IDE - Find a symbol in the library I've inherited a flash project (my first) that has many existing symbols in the library. They are organized in a large complex hierarchy of folders. Often, I find a reference to a symbol in actionscript code, but can't find the symbol in the library. The "Find" feature only searches for instances of a symbol. If none exist, is it possible to find a symbol in the library without manually checking each folder?
A: This will be helpful
http://www.gskinner.com/products/panelpack1/gSearch.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java date format incompatible with xquery xs:date format, how to fix? In java, when using SimpleDateFormat with the pattern:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
the date is outputted as:
"2002-02-01T18:18:42.703-0700"
In xquery, when using the xs:dateTime function, it gives the error:
"Invalid lexical value [err:FORG0001]"
with the above date. In order for xquery to parse properly, the date needs to look like:
"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string
which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.
I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.
Thanks!
A: OK, the linked to forum post DID help, thank you. I did however find a simpler solution, which I include below:
1) Use Apache commons.lang java library
2) Use the following java code:
//NOTE: ZZ on end is not compatible with jdk, but allows for formatting
//dates like so (note the : 3rd from last spot, which is iso8601 standard):
//date=2008-10-03T10:29:40.046-04:00
private static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ";
DateFormatUtils.format(new Date(), DATE_FORMAT_8601)
A: Well, I did run into a problem - it doesn't appear to me (and I could be wrong) that there was any way to convert from and ISO string that DateUtils (from apache commons lang) creates, back to a date!
ie. apache commons will format it the way I would like, but not convert it back to a date again
So, I switched to JodaTime, and its much easier since its based on ISO8601 - here is the code:
public static void main(String[] args) {
Date date = new Date();
DateTime dateTime = new DateTime(date);
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String dateString = fmt.print(dateTime);
System.out.println("dateString=" + dateString);
DateTime dt = fmt.parseDateTime(dateString);
System.out.println("converted date=" + dt.toDate());
}
A: Great find regarding commons.lang.java! You can even save yourself from creating your own format string by doing the following:
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());
A: Try this:
static public String formatISO8601(Calendar cal) {
MessageFormat format = new MessageFormat("{0,time}{1,number,+00;-00}:{2,number,00}");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(cal.getTimeZone());
format.setFormat(0, df);
long zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L;
int zoneHrs = (int) (zoneOff / 60L);
int zoneMins = (int) (zoneOff % 60L);
if (zoneMins < 0)
zoneMins = -zoneMins;
return (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) }));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I find the version of Apache running without access to the command line? I need to either find a file in which the version is encoded or a way of polling it across the web so it reveals its version. The server is running at a host who will not provide me command line access, although I can browse the install location via FTP.
I have tried HEAD and do not get a version number reported.
If I try a missing page to get a 404 it is intercepted, and a stock page is returned which has no server information on it. I guess that points to the server being hardened.
Still no closer...
I put a PHP file up as suggested, but I can't browse to it and can't quite figure out the URL path that would load it. In any case I am getting plenty of access denied messages and the same stock 404 page. I am taking some comfort from knowing that the server is quite robustly protected.
A: Rarely, a hardened HTTP server is configured to give no server information or misleading server information. In those scenarios if the server has PHP enabled you can add:
<?php phpinfo(); ?>
in a file and browse to it and look for the
_SERVER["SERVER_SOFTWARE"]
entry. This is susceptible to the same hardening lack of information/misleading though I would imagine that it's not altered often, because this method first requires access to the machine to create the PHP file.
A: Warning, some Apache servers do not always send their version number when using HEAD, like in this case:
HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 13:09:45 GMT
Server: Apache
X-Powered-By: PHP/5.2.6RC4-pl0-gentoo
Set-Cookie: PHPSESSID=a97a60f86539b5502ad1109f6759585c; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Connection: close
Content-Type: text/html
Connection to host lost.
If PHP is installed then indeed, just use the php info command:
<?php phpinfo(); ?>
A: httpd -v will give you the version of Apache running on your server (if you have SSH/shell access).
The output should be something like this:
Server version: Apache/2.2.3
Server built: Oct 20 2011 17:00:12
As has been suggested you can also do apachectl -v which will give you the same output, but will be supported by more flavours of Linux.
A: The level of version information given out by an Apache server can be configured by the ServerTokens setting in its configuration.
I believe there is also a setting that controls whether the version appears in server error pages, although I can't remember what it is off the top of my head. If you don't have direct access to the server, and the server administrator is competent and doesn't want you to know the version they're running... I think you may be SOL.
A: The method
Connect to port 80 on the host and send it
HEAD / HTTP/1.0
This needs to be followed by carriage-return + line-feed twice
You'll get back something like this
HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 12:39:43 GMT
Server: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0
Last-Modified: Thu, 02 Aug 2007 20:50:09 GMT
ETag: "438118-197-436bd96872240"
Accept-Ranges: bytes
Content-Length: 407
Connection: close
Content-Type: text/html; charset=UTF-8
You can then extract the apache version from the Server: header
Typical tools you can use
You could use the HEAD utility which comes with a full install of Perl's LWP library, e.g.
HEAD http://your.webserver.com/
Or, use the curl utility, e.g.
curl --head http://your.webserver.com/
You could also use a browser extension which lets you view server headers, such as Live HTTP Headers or Firebug for Firefox, or Fiddler for IE
Stuck with Windows?
Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this
telnet your.webserver.com 80
Then type (carefully, your characters won't be echoed back)
HEAD / HTTP/1.0
Press return twice and you'll see the server headers.
Other methods
As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it
<?php phpinfo() ?>
Request the page with a web browser and you should see the Apache version reported there.
You could also try and use PHPShell to have a poke around, try a command like
/usr/sbin/apache2 -V
A: Telnet to the host at port 80.
Type:
get / http1.1
::enter::
::enter::
It is kind of an HTTP request, but it's not valid so the 500 error it gives you will probably give you the information you want. The blank lines at the end are important otherwise it will just seem to hang.
A: If they have error pages enabled, you can go to a non-existent page and look at the bottom of the 404 page.
A: In the default installation, call a page that doesn't exist and you get an error with the version at the end:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please
check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
10/03/08 14:41:45
Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5
A: Your best option is through PHP:
All version requests from the client side cannot be trusted since your Apache could be configured with ServerTokens Prod and ServerSignature Off. See: http://www.petefreitag.com/item/419.cfm
A: Simply use something like the following - the string should be there already:
<?php
if(isset($_SERVER['SERVER_SOFTWARE'])){
echo $_SERVER['SERVER_SOFTWARE'];
}
?>
A: Use this PHP script:
$version = apache_get_version();
echo "$version\n";
Se apache_get_version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
} |
Q: Can I add a PHP array key without an assigned value in a class variable? I am currently plowing my way through IBM's tutorial on CakePHP
At one point I run into this snippet of code:
<?php
class Dealer extends AppModel {
var $name = 'Dealer';
var $hasMany = array (
'Product' => array(
'className' => 'Product',
'conditions'=>, // is this allowed?
'order'=>, // same thing here
'foreignKey'=>'dealer_id'
)
);
}
?>
When I run it I get the following error-message: "Parse error: syntax error, unexpected ',' in /Applications/MAMP/htdocs/cakephp/app/models/product.php on line 7"
I'm a n00b at PHP so my question is: is it allowed to make an array with keys without assigned values? Has anybody played around with this tut and know what is up?
A: Assign the value null instead of leaving anything out. The manual says
isset() will return FALSE if testing a variable that has been set to NULL
<?php
class Dealer extends AppModel
{
var $name = 'Dealer';
var $hasMany = array(
'Product' => array(
'className' => 'Product',
'conditions' => null,
'order' => null,
'foreignKey' => 'dealer_id'
)
);
}
?>
This works fine.
A: It is legal, though as far as I'm aware, you have to explicitly say it's 'empty' by assigning null to it,
$hasMany = array ('Product' => array(
'className' => 'Product',
'conditions'=> null, // is this allowed?
'order'=> null, // same thing here
'foreignKey'=>'dealer_id'));
The example you've given sounds very wrong, and probably shouldn't work, as it isn't.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "CURLE_OUT_OF_MEMORY" error when posting via https I am attempting to write an application that uses libCurl to post soap requests to a secure web service. This Windows application is built against libCurl version 7.19.0 which, in turn, is built against openssl-0.9.8i. The pertinent curl related code follows:
FILE *input_file = fopen(current->post_file_name.c_str(), "rb");
FILE *output_file = fopen(current->results_file_name.c_str(), "wb");
if(input_file && output_file)
{
struct curl_slist *header_opts = 0;
CURLcode rcd;
header_opts = curl_slist_append(header_opts, "Content-Type: application/soap+xml; charset=utf8");
curl_easy_reset(curl_handle);
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, output_file);
curl_easy_setopt(curl_handle, CURLOPT_READDATA, input_file);
curl_easy_setopt(curl_handle, CURLOPT_URL, fs_service_url);
curl_easy_setopt(curl_handle, CURLOPT_POST, 1);
curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, header_opts);
rcd = curl_easy_perform(curl_handle);
if(rcd != 0)
{
current->curl_result = rcd;
current->curl_error = curl_easy_strerror(rcd);
}
curl_slist_free_all(header_opts);
}
When I attempt to execute the URL, curl returns an CURLE_OUT_OF_MEMORY error which appears to be related to a failure to allocate an SSL context. Has anyone else encountered this problem before?
A: I had the same problem, just thought I'd add the note that rather than calling the OpenSsl export SSL_library_init directly it can be fixed by adding the flag CURL_GLOBAL_SSL to curl_global_init
A: After further investigation, I found that this error was due to a failure to initialise the openSSL library by calling SSL_library_init().
A: I encountered the same symptom after upgrading to Ubuntu 16.04 as described in this answer. The solution was to Use TLS like so.
curl_easy_setopt(curl_, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2));
Apparently SSLv3 was disabled on Ubuntu 16.04.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: PHP utf8 problem I have some problems comparing an array with Norwegian characters with a utf8 character.
All characters except the special Norwegian characters(æ, ø, å) works fine.
function isNorwegianChar($Char)
{
$aNorwegianChars = array('a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', 'æ', 'Æ', 'ø', 'Ø', 'å', 'Å', '=', '(', ')', ' ', '-');
$iArrayLength = count($aNorwegianChars);
for($iCount = 0; $iCount < $iArrayLength; $iCount++)
{
if($aNorwegianChars[$iCount] == $Char)
{
return true;
}
}
return false;
}
If anyone has any idea about what I can do pleas let me know.
Update:
The reason for needing this is that I'm trying to parse a text file that contains lines with Norwegian and Chinese words, like a dictionary. I want to split the line in to strings, one containing the Norwegian word and one containing the Chinese. This will later be inserted in a database. Example lines:
impulsiv 形 衝動的
imøtegå 動 反對,反駁
imøtekomme 動 符合
alkoholmisbruk(er) 名 濫用酒精 (名 濫用酒精的人)
alkoholpåvirket 形 受酒精影響的
alkotest 名 呼吸性酒精測試
alkymi(st) 名 煉金術 (名 煉金術士)
all, alt, alle, 形 全部, 所有
As you can see there might be spaces between the words so I can not use something easy like explode to split between the Chinese and Norwegian words. What I do is use the isNorwegianChar and loop through the line until I find a char that is not in the array.
The problem is that it æ, ø and å is not returned as a Norwegian character and it think the Chinese word has started.
Here is the code:
//Open file.
$rFile = fopen("norsk-kinesisk.txt", "r");
// Loop through the file.
$Count = 0;
while(!feof($rFile))
{
if(40== $Count)
{
break;
}
$sLine = fgets($rFile);
if(0 == $Count)
{
$sLine = mb_substr($sLine, 3);
}
$iLineLength = strlen($sLine);
$bChineseHasStarted = false;
$sNorwegianWord = '';
$sChineseWord = '';
for($iCount2 = 0; $iCount2 < $iLineLength; $iCount2++)
{
$char = mb_substr($sLine, $iCount2, 1);
if(($bChineseHasStarted === false) && (false == isNorwegianChar($char)))
{
$bChineseHasStarted = true;
}
if(false === $bChineseHasStarted)
{
$sNorwegianWord .= $char;
}
else
{
$sChineseWord .= $char;
}
//echo $char;
}
$sNorwegianWord = trim($sNorwegianWord);
$sChineseWord = trim($sChineseWord);
$Count++;
}
fclose($rFile);
A: First of all, and I'll get to UTF-8 later if nobody else answers, iterating like you are is a very bad way to search through an array. PHP has built-in functions just for that:
http://fr.php.net/array_search
So you might want to give that a try and see if it helps with your problem. Also make sure that the PHP file you're writing is also encoded in UTF-8!
UPDATE:
Try the following code, which works just fine on my server. If it doesn't work check that PHP is configured to work with UTF-8 by default, or add the necessary ini_set calls.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head><title>norvegian utf-8 test</title>
<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />
</head>
<body>
<?php
function isSpecial($char) {
$special_chars = array("æ", "ø", "å", "か");
return (array_search($char, $special_chars) !== false);
}
if (isset($_REQUEST["char"])) {
echo $_REQUEST["char"].(isSpecial($_REQUEST["char"])?" (true)":" (false)");
}
?>
<form method="POST" accept-charset="UTF-8">
<input type="text" name="char">
<input type="submit" value="submit">
</form>
</body>
</html>
A: If your PHP script file has an ANSI encoding, instead of UTF-8, then on the byte-level those norwegian characters will be different from what they would be if they were encoded in UTF-8. Since PHP is a byte-processing language, not a text-processing language, it duly compares the byte sequences and concludes they don't match.
To resolve this, you can either make sure that your PHP script has the same encoding as the character set you're comparing against, or you can use the iconv or mbstring libraries to convert to appropriate character sets.
Also, if you haven't read it, read this: http://www.joelonsoftware.com/articles/Unicode.html
Update:another point you take into account is to make sure that what you're passing into this function is what you think it is. If you're looping across a string one character at a time with the array indexing operator, it won't work, because your UTF-8 string might use two bytes (two array index positions) to store one character. There are functions in mbstring to copy out text from strings based on character positions, not byte positions.
A: I finally figured it out. It might not be a nice way to do it, but it works.
It seems like the array I was working with was in a different charset than the input character. I solved this by making a string of all the array elements and then use mb_strpos to search for the characters. So the only change to the code is the isNorwegianChar function. The new function looks like this:
function isNorwegianChar($Char)
{
$sNorwegianChars = "'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZæÆøØåÅ=() -,";
if(mb_strpos($sNorwegianChars, $Char))
{
return true;
}
else
{
return false;
}
}
Thanks for all the help!
A: See if you have mbstring extension installed
A: From what I know, your best bet is to install the mbstring (http://www.php.net/manual/en/ref.mbstring.php) extention if you have access to the webserver.
A: Try using the functions for utf8-encoding and decoding. might help
A: As the problem is to separate Norvegian word(s) from Chinese ones, why don't you use an explicit glyph to do so (I personnaly like "¶"), instead of relying on an algorithm ?
impulsiv¶形 衝動的
Then use mb-split, or mb-substr combined with mb-strpos.
You can easily replace it with a space if you need to output the string!
Sadly, PCRE in PHP doesn't allow us to use \p with script names.
(look for "InMusicalSymbols" in regexp.reference, in § "Unicode character properties", to understand what I mean)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I repeat a string a variable number of times in C++? I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there a direct way to do this using either std::strings or char* strings?
E.g., in Python you could simply do
>>> "." * 5 + "lolcat"
'.....lolcat'
A: You should write your own stream manipulator
*
*http://www.two-sdg.demon.co.uk/curbralan/papers/WritingStreamManipulators.html
cout << multi(5) << "whatever" << "lolcat";
A: There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:
std::string(5, '.')
This is a contrived example of how you might use an ostringstream to repeat a string n times:
#include <sstream>
std::string repeat(int n) {
std::ostringstream os;
for(int i = 0; i < n; i++)
os << "repeat";
return os.str();
}
Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.
A: Here's an example of the string "abc" repeated 3 times:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
int main() {
ostringstream repeated;
fill_n(ostream_iterator<string>(repeated), 3, string("abc"));
cout << "repeated: " << repeated.str() << endl; // repeated: abcabcabc
return 0;
}
A: In the particular case of repeating a single character, you can use std::string(size_type count, CharT ch):
std::string(5, '.') + "lolcat"
This can't be used to repeat multi-character strings.
A: Use one of the forms of string::insert:
std::string str("lolcat");
str.insert(0, 5, '.');
This will insert "....." (five dots) at the start of the string (position 0).
A: For the purposes of the example provided by the OP std::string's ctor is sufficient: std::string(5, '.').
However, if anybody is looking for a function to repeat std::string multiple times:
std::string repeat(const std::string& input, unsigned num)
{
std::string ret;
ret.reserve(input.size() * num);
while (num--)
ret += input;
return ret;
}
A: As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.
While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:
#include <string>
#include <cstddef>
std::string repeat(std::string str, const std::size_t n)
{
if (n == 0) {
str.clear();
str.shrink_to_fit();
return str;
} else if (n == 1 || str.empty()) {
return str;
}
const auto period = str.size();
if (period == 1) {
str.append(n - 1, str.front());
return str;
}
str.reserve(period * n);
std::size_t m {2};
for (; m < n; m *= 2) str += str;
str.append(str.c_str(), (n - (m / 2)) * period);
return str;
}
We can also define an operator* to get something closer to the Python version:
#include <utility>
std::string operator*(std::string str, std::size_t n)
{
return repeat(std::move(str), n);
}
On my machine this is around 10x faster than the implementation given by Commodore, and about 2x faster than a naive 'append n - 1 times' solution.
A: I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation
http://www.java-samples.com/showtutorial.php?tutorialid=458
cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;
outputs
.....lolcat
A: You can use a C++ function for doing this:
std::string repeat(const std::string& input, size_t num)
{
std::ostringstream os;
std::fill_n(std::ostream_iterator<std::string>(os), num, input);
return os.str();
}
A: @Daniel provided an implementation that is significantly faster than other answers in its primary execution branch (where n > 1 and str is not empty). However, the corner cases are handled much more inefficiently than they could be.
This implementation corrects those issues:
#include <string>
#include <cstddef>
std::string repeat(size_t n, const std::string& str) {
if (n == 0 || str.empty()) return {};
if (n == 1) return str;
const auto period = str.size();
if (period == 1) return std::string(n, str.front());
std::string ret(str);
ret.reserve(period * n);
std::size_t m {2};
for (; m < n; m *= 2) ret += ret;
ret.append(ret.c_str(), (n - (m / 2)) * period);
return ret;
}
A benchmark comparison of the two implementations on quick-bench.com shows the following differences in these corner cases. Clang 13.0 is the first number and GCC 10.3 is the second. -O3 optimization in all cases.
*
*For n == 0, this implementation is (9x / 11x) faster.
*For str.empty() == true, it is (2.4x / 3.4x) faster.
*For n == 1 and str.size() > 1, it is (2.1x / 1.4x) faster.
*And for str.size() == 1, it is (1.3x / 1.2x) faster.
The problem with the original implementation boils down to passing str into the function by value. This invokes a copy of str on every call to repeat that is unnecessary in some of the corner cases; especially when n == 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "166"
} |
Q: What kind of damage could one do with a payment gateway API login and transaction key? Currently, I'm in the process of hiring a web developer who will be working on a site that processes credit cards. While he won't have the credentials to log into the payment gateway's UI he will have access to the API login and transaction key since it's embedded in the application's code.
I'd like to be aware of all the "what if" scenarios pertaining to the type of damage one could do with that information. Obviously, he can process credit cards but the money goes into the site owner's bank account so I'm not sure how much damage that could cause. Can anyone think of any other possible scenarios?
UPDATE: The payment gateway being used is Authorize.net.
A: Do they really need access to your production sites?
Don't store the key in your code, store it in your production database, or on a file on the production server.
A: Some good answers here, I'll just add that you'd probably have some trouble with PCI.
PCI-DSS specifically dictates separation of duties, isolation of production environments from dev/test, protection of encryption keys from anyone who does not require it, and more.
As @Matthew Watson said, rethink this, and dont grant production access to developers.
As an aside, if he can access the API directly, how do you ensure that "the money goes into the site owner's bank account"? Not to mention access to all that credit card data...
A: If the developer gets access to the raw credit card numbers that can become a bigger problem as your site can be associated with fraudulent activity, assuming the developer is a bad apple. (They could redirect account numbers, CCV, expiration date to another site, though this should be spottable through network tools and a comprehensive code review.)
Does the API perform the "$1.00" charge (or "$X.XX") to verify that a credit card can be charged a certain amount (and thus returning the result to the caller, such as "yes" or "no")? If so, it could be used to automate the validation of credit card account numbers traded on the Internet and abuse of such a system could lead back to you.
A: With any gateway I have worked with, the payment processor ties the API key to the specific IP or IP range of the site of the merchant. With that said, unless the malicious(?) code in question is executed on the same server as the merchant - there shouldn't be any security concerns in that regard.
If this is not the case for your merchant site - contact them and ask if this is feasible.
A: Does the payment gateway allow for reversal of charges? If so there is the possibility of a number of scams being run.
A: Does the site process refunds? Will it ever in the future?
If we're talking about nefarious uses, then the site owner might be investigated if lots of unauthorized purchases are made. How would that affect you if the owner is investigated?
A: From your description it seems that this developer will have access to the customer cards detail in which case the customers privacy may be compromised. You might consider wording the contract appropriately to make sure that this angle is covered.
However the main point is that if you're working on a sensitive project/information it's better for you to find people you could trust. Hiring a software house to do the job may save you some sleep later on.
A: First and foremost, it is best that you never store this type of information in plain text. Usually people take this as second-hand knowledge for credit card numbers (Sadly, only because of legal reasons), but any sort of private data that you don't want others with database/source-code access viewing should be encrypted. You should store the account information somewhere in a well encrypted format, and you should provide a test account for your developers to use on their development workstations. This way, only people with server access are able to see even the encrypted information.
This way, you can have a database on the developer's workstation with the test account's API information stored (hopefully encrypted) in it's local database, but when the code is mirrored onto the production server it will still use the live, real gateway information stored on the production server's database without extra code/configuration.
With this said, I don't think that a programmer with API authentication details can do too much. Either way, it's not worth the risk - in my opinion.
Hope this help.
PS: If something bad does end up happening, you can always generate a new key in the web interface on authorize.net after you've taken the precautions to make sure it wont happen again.
A: In the specific case of Authorize.Net they would not be able to do credits towards their own credit cards since Authorize.Net only allows this to be done on transactions performed through them within the last six months. The only exception being allowed if you are granted an exception for unlinked refunds. If you have signed the proper paperwork for this and someone has your API login and transaction key then can then process credits towards their own credit cards. The only way for you to catch this would be to monitor your statements carefully.
To help mitigate this you should change your transaction key immediately upon completion of the work they perform for you. That would render the key they have useless after 24 hours.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is using size() for the 2nd expression in a for construct always bad? In the following example should I expect that values.size() will be called every time around the loop? In which case it might make sense to introduce a temporary vectorSize variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.
double sumVector(const std::vector<double>& values) {
double sum = 0.0;
for (size_t ii = 0; ii < values.size(); ++ii) {
sum += values.at(ii);
}
}
Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.
A: Start with size() in the 'for' construct until you need to optimize for speed.
If it is too slow, look for ways to make it faster, such as using a temporary variable to hold the result of size.
A: No matter the optimisation settings, putting the .size() call in the second expression will be at most as performant as outlining the .size() call before the for-loop. That is:
size_t size = values.size();
for (size_t ii = 0; ii < size; ++ii) {
sum += values.at(ii)
}
will always perform at least as well as, if not better than:
for (size_t ii = 0; ii < values.size(); ++ii) {
sum += values.at(ii);
}
In practice, it probably wont matter, since outlining the .size() call is a common compiler optimisation. However, I do find the second version easier to read.
I find this even easier, though:
double sum = std::accumulate(values.begin(), values.end(), 0);
A: Worth noting that even if you are dealing with millions of items the overhead is going to be negligible.
In any case this should really be written using iterator - as there may be more overhead accessing a specific example.
There is really no way that the compiler can assume that size() won't change - because it could do..
If the order of iteration isn't important then you could always write it as which is slightly more efficient.
for (int i=v.size()-1; i>=0 ;i--)
{
...
}
A: This isn't part of the question but why are you using at in your code in place of the subscript operator []?
The sense in at is to ensure that no operation on an invalid index occurs. However, this will never be the case in your loop since you know from your code what the indices are going to be (always assuming single-threadedness).
Even if your code contained a logical error, causing you to access an invalid element, at in this place would be useless because you don't expect the resulting exception and hence you don't treat it (or do you enclose all of your loops by try blocks?).
The use of at here is misleading because it tells the reader that you (as a programmer) don't know what values the index will have – which is obviously wrong.
I agree with Curro, this is a typical case for the use of iterators. Although this is more verbose (at least if you don't use constructs like Boost.Foreach), it is also much more expressive and safer.
Boost.Foreach would allow you to write the code as follows:
double sum = 0.0;
foreach (double d, values)
sum += d;
This operation is safe, efficient, short and readable.
A: It doesn't matter at all. The performance overhead of .at() is so large (it contains a conditional throw statement) that a non-optimized version will spend most of its time there. An optimizing compiler smart enough to eliminiate the conditional throw will necessarily spot that size() does not change.
A: Here's one way to do it that makes it explicit - size() is called only once.
for (size_t ii = 0, count = values.size(); ii < count; ++ii)
Edit: I've been asked to actually answer the question, so here's my best shot.
A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.
Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.
P.S. I wrote this before I read Benoit's answer carefully, I believe we're in complete agreement.
A: It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.
I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.
Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.
If it will be called thousands of times, then I would use the temporary.
Some might call this premature optimization, but I would tend to disagree with that assessment.
While you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance.
I have a hard time considering what is a refactoring to be an optimization. But in the end, this is along the lines of "you say tomato, I say tomato"...
A: I agree with Benoit. The introduction of a new variable, especially an int or even a short will have a bigger benefit that calling it each time.
It's one less thing to worry about if the loop ever gets large enough that it may impact performance.
A: The size method from std::vector should be inlined by the compiler, meaning that every call to size() is replaced by its actual body (see the question Why should I ever use inline code for more information about inlining). Since in most implementations size() basically computes the difference between end() and begin() (which should be inlined too), you don't have to worry too much about loss of performance.
Moreover, if I remember correctly, some compilers are "smart" enough to detect the constness of an expression in the second part of the for construct, and generate code that evaluates the expression only once.
A: If you hold the size of the vector in a temporary variable, you will be independent of the compiler.
My guess is, that most compilers will optimize the code in a way, that size() will be called only once. But using a temporary variable will give you a guarantee, size() will only be called once!
A: The compiler will not know if the value of .size() changes between calls, so it won't do any optimizations. I know you just asked about the use of .size(), but you should be using iterators anyway.
std::vector<double>::const_iterator iter = values.begin();
for(; iter != values.end(); ++iter)
{
// use the iterator here to access the value.
}
In this case, the call to .end() is similar to the problem you expose with .size(). If you know the loop does not perform any operation in the vector that invalidates the iterators, you can initialize an iterator to the .end() position prior to enter the loop and use that as your boundary.
A: In such cases using iterators is cleaner - in some it's even faster. There's only one call to the container - getting the iterator holding a pointer to the vector member if there are any left, or null otherwise.
Then of course for can become a while and there are no temporary variables needed at all - you can even pass an iterator to the sumVector function instead of a const reference/value.
A: Always write code the first time exactly as you mean it. If you are iterating over the vector from zero to size(), write it like that. Do not optimise the call to size() into a temporary variable unless you have profiled the call to be a bottleneck in your program that needs optimising.
In all likelihood, a good compiler will be able to optimise away the call to size(), particularly given that the vector is declared as const.
A: If you were using a container where size() was O(n) (like std::list) and not O(1) (like std::vector), you would not be iterating through that container using indices. You would be using iterators instead.
Anyway, if the body of the loop is so trivial that recalculating std::vector::size() matters, then there is probably a more efficient (but possibly platform-specific) way to do the calculation, regardless of what it is. If the body of the loop is non-trivial, recalculating std::vector::size() each time is unlikely to matter.
A: *
*If you are modifying the vector (adding or removing elements) in the for loop then you should not use a temporary variable since this could lead to bugs.
*If you are not modifying the vector size in the for loop then I would all the time use a temporary variable to store the size (this would make your code independant on the implementation details of vector::size.
A: Most, maybe even all, standard implementations of size() will be inlined by the compiler to what would be the equivalent of a temporary or at most a pointer dereference.
However, you can never be sure. Inlining is about as hidden as these things get, and 3rd party containers may have virtual function tables - which means you may not get inlined.
However, seriously, using a temporary reduces readability slightly for almost certainly no gain. Only optimise to a temporary if profiling says it is fruitful. If you make these micro optimisations everywhere, your code could become unreadable, perhaps even for yourself.
As a slight aside, no compiler would optimise size() to one of call assigning to a temporary. There is almost no guarantee of const in C++. The compiler cannot risk assuming size() will return the same value for the whole loop. For example. Another thread could change the vector in between loop iterations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to make some NAnt tasks quiet? I am using MailLogger to send a message about a failed/successful release. I would like to make the mail body simple and easy to read. How can I suppress output for some particular tasks?
A: Would it be too simple if you'd call nant with the -quiet switch?
EDIT: and for the tasks whose output you are interested in you can set the verbose attribute to true.
A: Another option would be to use the xmllogger instead of the maillogger, to output an xml file which can then be processed using a xslt stylesheet. Use the stylesheet to filter out information you don't need. If you want it to be mailed to your inbox you could use the mail task from nant and include the transformed file as an attachment or if you transformed it to txt/html you could also use it to fill the body.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Agent-based modeling resources I would like to know what kind of toolkits, languages, libraries exist for agent-based modeling and what are the pros/cons of them?
Some examples of what I am thinking of are
Swarm, Repast, and MASS.
A: I found a survey from June 2009 that answer your question:
Survey of Agent Based Modelling and Simulation Tools
Au. R.J. Allan
Abstract
Agent Based Modelling and Simulation is a computationally
demanding technique based on discrete event simulation and having its
origins in genetic algorithms. It is a powerful technique for
simulating dynamic complex systems and observing “emergent” behaviour.
The most common uses of ABMS are in social simulation and optimisation
problems, such as traffic flow and supply chains. We will investigate
other uses in computational science and engineering. ABMS has been
adapted to run on novel architectures such as GPGPU (e.g. nVidia using
CUDA). Argonne National Laboratory have a Web site on Exascale ABMS
and have run models on the IBM BlueGene with funding from the SciDAC
Programme. We plan to organise a workshop on ABMS methodolgies and
applications in summer of 2009. Keywords agent based modelling,
Archaeology
http://epubs.cclrc.ac.uk/bitstream/3637/ABMS.pdf
A: I also recommend NetLogo. It is an IDE+environment+programming language based on logo (which was based on Lisp) which lets you build multi-agent models extremely fast. I have found that I can reproduce (simulate) algorithms from research articles in a couple of hours, algorithms that would have taken weeks to implement with other libraries.
You can check some of my models at this page.
A: I got introduced to Dramatis at OSCON 2008, it is an Agent based framework for Ruby and Python. The author (Steven Parkes) has some references in his blog and is working at running a language agnostic Actors discussion list.
This page at erights.org has a great set of references to, what I think are, the core papers that introduce and explore the Actors message passing model.
A: you should also have a look at Madkit and Turtlekit
A: There is also a pretty good link in wikipedia:
http://en.wikipedia.org/wiki/Comparison_of_agent-based_modeling_software
A: On the modelling side, have a look at FAML, an agent-oriented modelling language. This is a pretty academic paper, but it may help depending on your interests: http://ieeexplore.ieee.org/xpl/freepre_abs_all.jsp?isnumber=4359463&arnumber=4967615
A: I know this is an old thread, but I thought it would not hurt to add some extra info. There is a great new website which is dedicated to agent-based modeling. The site contains links to papers, tutorials, tools, resources, and researchers working on agent-based modeling in a number of fields.
A: Old thread, but for completeness there is also Anylogic and pyabm which can be used for ABMs.
I have experience programming agent-based models in several environments / languages. My opinion is that if you want to implement a relatively simple model, use Netlogo. It's also possible to use Netlogo for heavy-duty models as well (I've done this successfully), but at some point the flexibility of a programming language like java/python/c++ outweighs the convenience of the native methods available in Netlogo, especially when performance becomes a major issue.
Repast is becoming a bit bloated. If you are an experienced programmer, all you really need to start building an ABM is the ability to schedule events and draw random numbers. The rest (defining agents / environments and their behaviors) you can craft on your own. When it comes to managing the objects in your model, use the regular data structures you're used to (arrays / hashes / trees / etc.). To this end, I'm developing a very lightweight Java library called "ABMUtils" (on github) that implements a scheduler and wraps a random number generator. This is in the early development stage but I expect to flesh things out (keeping it simple) over the coming months.
A: If you are an evolutionary economist you can also check Laboratory for Simulation Development (LSD).
A: PHP and Java developers should take a look at KATO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Extracting PNG images from Delphi 2009 imagelist The TImageList of Delphi 2009 has support for PNG images by adding them in the imagelist editor. Is there any way to extract a TPngImage from a TImagelist and preserving the alpha channel?
What I want to do is actually to extract the images from one TImageList, make a disabled version of them and then add them to another TImageList. During this operation I would of course like to preserve the alpha channel of the PNG images.
A: I did something like this with Delphi 2006.
TImageList contains a protected method GetImages. It can be accessed using the "protected bug"
type
TGetImageImageList = class (TImageList) // Please use a better name!
end;
You can cast the imagelist to the TGetImageImageList to get to the GetImages.
begin
TGetImageList(ImageList).GetImages(index, bitmap, mask);
end;
Bitmap contains the bitmap and mask is a black and white bitmap that determines the transparant sections.
You now can change the bitmap and store it using:
function Add(Image, Mask: TBitmap): Integer;
I hope this gives you enough pointers to explore further.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the best standard to use for business document exchange (invoices, POs etc)? If I need to implement sending and receiving of business documents from system to system (invoices, POs, remittance advice, etc) what standard would you recommend for best interop and why? It could be XML or otherwise.
A: UBL (Universal Business Language) is the latest attempt to do this, managed by OASIS. The problem is that the holy grail of business document interop is really a long way off, if realistic at all. That is why products like Biztalk exist. Biztalk's primary purpose is to take the document in one partner's format and convert it into your format, or vice versa.
Even huge standards like ANSI X12 and Edifact were problematic because even when two partners exchanged documents using an agreed standard there were usually enough differences in the way the documents were utilized that it required custom coding to process them.
My suggestion is to expose a clean and easy to understand XML format that very closely matches your business needs and let your partners use whatever method they currently use with other partners to process your document. Trying to follow an industry standard will be much more work and probably provide little benefit.
A: I would look at (in this order):
*
*Industry-specific formats. Always your best choice if you have a homogeneous trading group.
*cXML or XCBL if you want an XML solution with an established standard.
*X12 if you have unlimited time, money, and willing partners.
*custom XML only if you have requirements outside a standard or such a small amount of data to transmit that the standard would bloat your documents too much.
This, of course, all depends on the problem domain. I would think about these questions:
*
*Are you in an industry with specific format or regulatory requirements? For instance, are there details like the chemical composition of a gas that you're ordering? Are there hazardous materials that require special orders or handling?
*Does your industry have a specific format already or do you need a generic one? Chem/Gas, Retail, Big Oil, Airlines, Financial Services, and many others already have formats and sometimes networks established.
*Do you work with corporate purchasers who have procurement applications? If so, I'd take a look at cXML or XCBL which handles the PunchOut standard which enables purchasing systems to order from online catalogs.
*What is the sophistication of your partners? EDI is old and powerful, but really hard to understand. People new to the process are more comfortable with XML-based formats.
*What is your position in the market? Can you drive a standard for your partners or will they dictate a format to you? In which case, will you need to adopt several standards? Who will translate between them?
A: The standard is X12. That's pretty much it. See the EDI page on Wikipedia.
A: There is the ebXML standard, which covers not only document formats but also the processes between business entities.
A: There are various standard for doing this like
SWIFT - TSU
Bolereo
Twist
However none of the standards have been fully adopted/accepted by the industry and hence they would not be interop.
The other methodology is using a documents flow management system where by you scan and store all the documents as images and build a work flow around sending and receiving these.
A: PDF - everyone has it, its cross platform and it can handle any document type. No good if you want to edit it though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is it possible to select a specific tab in OSX Terminal.app using keyboard shortcuts? I know I can cycle through my tabs using cmd+{ or cmd+}, but is it possible to select a specific tab (i.e. cmd+3 for the third tab in iTerm) in Leopards' Terminal.app?
A: This is an option. Tab Switching in Terminal
A: Yes it is, you use Command-1, Command-2 etc.
Have a look under the Window menu, and you'll see the windows listed with their shortcut equivalent. (The 'clover-leaf' is the symbol for the Command key - also known as the Apple key.)
My apologies - missed the fact you were referring to Tabs first time around. I don't believe there is any other keyboard shortcut to switch between Tabs beyond Cmd-{ and }. Perhaps if that's important, don't group them in the first place? Leave them as separate windows?
A: I would highly suggest using GNU Screen if you really need tabs that much. I have a particular .screenrc file that makes life easier, just put the following in your home directory in a file called .screenrc:
defscrollback 1024
hardstatus on
hardstatus alwayslastline
hardstatus string "%{.bW}%-w%{.rW}%n %t%{-}%+w %=%{..G} %H %{..Y} %m/%d %C%a "
Also, when starting screen, I run screen -c ~/.screenrc.programming which looks like this:
source $HOME/.screenrc
screen -t World
screen -t Server
screen -t Console
screen -t Command
screen -t Editor
screen -t MySQL
This will open a bunch of 'tabs' that you can switch between using Ctrl-A,n and Ctrl-A,p or Ctrl-A followed by a number to switch directly to one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How to combine cascading updates/deletes between SQL Server and NHibernate? I am writing an application with a hand-crafted domain model (classes) and a hand-crafted data model (tables/relationships), and letting NHibernate take care of the mapping.
Is it best to tell the database to perform cascading updates or deletes or to tell NHibernate to do it (cascade="all-delete-orphan")? Can they both be set up to do it at the same time?
A: I prefer to let NHibernate do this for me. It's easier to setup and it works well.
cascade: all-delete-orphan is something that you wouldn't be able to do in SQL without a trigger, so there's another reason
A:
Can they both be set up to do it at the same time?
I think if you try, you might get NHibernate complaining, as most of it's operations check the row count to ensure that the expect number of rows were inserted/updated/deleted.
As Ben says, get NHibernate to do it.
Ultimately, NHibernate (and ORMs in general) let you think of the database as a storage and retrieval mechanism. You still want to create constraints, primary keys, foreign keys, and indexes, but the ORM should obey these rules anyway.
As with any data-access scenerio, if you find yourself creating complex constraints in the database, then remember that these rules will have to be duplicated in your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to show the loading indicator in the top status bar I have noticed that some apps like Safari and Mail show a loading indicator in the status bar (the bar at the very top of the phone) when they are accessing the network. Is there a way to do the same thing in SDK apps, or is this an Apple only thing?
A: You need to take care of hiding the activity indicator also once your network call is done.
If you use AFNetworking, then you don't need to do much.
Do following changes in AppDelegate Class:
*
*Import AFNetworking/AFNetworkActivityIndicatorManager.h
*Put this in didFinishLaunchingWithOptions:
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]
A: I've found the following macros pretty useful!
#define ShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES
#define HideNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = NO
So you can just call ShowNetworkActivityIndicator(); or HideNetworkActivityIndicator(); from within your app (as long as the header is included of course!).
A: I wrote a singleton that solves the problem of multiple connections by keeping a counter of what is happening (to avoid removing the status when a connection returns but another one is still active):
The header file:
#import <Foundation/Foundation.h>
@interface RMActivityIndicator : NSObject
-(void)increaseActivity;
-(void)decreaseActivity;
-(void)noActivity;
+(RMActivityIndicator *)sharedManager;
@end
and implementation:
#import "RMActivityIndicator.h"
@interface RMActivityIndicator ()
@property(nonatomic,assign) unsigned int activityCounter;
@end
@implementation RMActivityIndicator
- (id)init
{
self = [super init];
if (self) {
self.activityCounter = 0;
}
return self;
}
-(void)increaseActivity{
@synchronized(self) {
self.activityCounter++;
}
[self updateActivity];
}
-(void)decreaseActivity{
@synchronized(self) {
if (self.activityCounter>0) self.activityCounter--;
}
[self updateActivity];
}
-(void)noActivity{
self.activityCounter = 0;
[self updateActivity];
}
-(void)updateActivity{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = (self.activityCounter>0);
}
#pragma mark -
#pragma mark Singleton instance
+(RMActivityIndicator *)sharedManager {
static dispatch_once_t pred;
static RMActivityIndicator *shared = nil;
dispatch_once(&pred, ^{
shared = [[RMActivityIndicator alloc] init];
});
return shared;
}
@end
Example:
[[RMActivityIndicator sharedManager]increaseActivity];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:self.networkReceiveProcessQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[[RMActivityIndicator sharedManager]decreaseActivity];
}
A: It's in UIApplication:
For Objective C:
Start:
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
End:
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
For swift :
Start
UIApplication.shared.isNetworkActivityIndicatorVisible = true
End
UIApplication.shared.isNetworkActivityIndicatorVisible = false
A: It might also be helpful to make sure you are running it on the main thread as it is UI related.
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
});
A: As many have said, there is no network activity indicator for the iPhone X and probably for the other new iPhones with the notch.
I came across this incredible library written by Ortwin Gentz, FutureTap:
https://github.com/futuretap/FTLinearActivityIndicator
It puts the indicator right back where it was when the iPhone X was initially released, many would remember the Knight Rider type of indicator.
This library is available for Swift 4.2, so you will need to change the Swift Language settings, as described here:
Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'
A: A single line code to do that:
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
A: The status bar network activity indicator was deprecated in iOS 13.
Using UIApplication.shared.isNetworkActivityIndicatorVisible = true will not work anymore.
The deprecation message says:
Provide a custom network activity UI in your app if desired.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "123"
} |
Q: Unable to serialize a property on a control Background
I am trying to create a copy of a business object I have created in VB.NET. I have implemented the ICloneable interface and in the Clone function, I create a copy of the object by serializing it with a BinaryFormatter and then de-serializing straight back out into another object which I return from the function.
The class I am trying to serialize is marked as "Serializable" along with the child objects that are contained within the class.
I have tested that the clone method works by writing code similar to the following:
Dim obj as New Sheep()
Dim dolly as Sheep = obj.Clone()
All works fine at this point.
Problem
I have a custom windows forms control which inherits from a 3rd party control. This custom control basically contains the object which I want to clone (as this object ultimatly feeds the 3rd party control).
I want to create a clone of the object within the windows form control so that I can allow the user to manipulate the properties whilst having the option of cancelling the changes and reverting the object back to how it was before they made the changes. I would like to take the copy of the object before the user starts making changes and hold onto it so I have it ready if they press cancel.
My thought would be to write code along the lines of the following:
Dim copy as Sheep = MyControl.Sheep.Clone()
Then allow the user to manipulate the properties on MyControl.Sheep. When I attempt to do this however, the clone method throws an exception stating:
Type 'MyControl' in Assembly 'My_Assembly_Info_Here' is not marked as serializable
This error is thrown at the point where I call BinaryFormatter.Serialize(stream,Me).
I have tried creating a method on MyControl that returns a copy of the object and also first assigning MyControl.Sheep to another variable and then cloning the variable but nothing seems to work. However, creating a new instance of the object directly and cloning it works fine!
Any idea's where I am going wrong?
Solution
Marc's answer helped point me in the right direction on this one. This blog post from Rocky Lhotka explains the problem and how to solve it.
A: Do you have an event that the UI is subscribing to? A {Foo}Changed event if data-binding, or perhaps INotifyPropertyChanged?
You might have to mark the event backing field as [NonSerialized] (or however attributes look in VB - I'm a C# person...). If you are using field-like-events (i.e. the abbreviated syntax without add/remove), then mark the entire event with [field: NonSerialized] (again, translate to VB).
A: An obvious question, but are you sure that you don't have a reference to MyControl from your Sheep object; be it an object or a list or anything? If this is the case this is what is preventing you from cloning your business object.
The more than likely candidates would be a .Parent or .Tag property.
A: In third party libraries if something is not marked as serializable it should not be serialized for a good reason, but often its not serializable because the developer just simply didn't include it. You can use reflection to make a copy of the public properties of the control and return its state to your reflected version on a cancel. There are performance implications to this approach but because you are working at the UI tier I imagine it won't be much of a worry. This method is not guaranteed error free; public properties do not necessarily represent the entire state of a class and setting some properties may have side effects (they shouldn't, but you didn't write the code, so either ILDasm it and see or hope for the best).
Additionally not all of the types of the properties may be serializable, in which case you need to go further by manually writing serialization routines for those types (and possibly those type's properties).
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
public class NonSerializableSheep
{
public NonSerializableSheep() { }
public string Name { get; set; }
public int Id { get; set; }
// public read only properties can create a problem
// with this approach if another property or (worse)
// a group of properties sets it
public int Legs { get; private set; }
public override string ToString()
{
return String.Format("{0} ({1})", Name, Id);
}
}
public static class GhettoSerializer
{
// you could make this a factory method if your type
// has a constructor that appeals to you (i.e. default
// parameterless constructor)
public static void Initialize<T>(T instance, IDictionary<string, object> values)
{
var props = typeof(T).GetProperties();
// my approach does nothing to handle rare properties with array indexers
var matches = props.Join(
values,
pi => pi.Name,
kvp => kvp.Key,
(property, kvp) =>
new {
Set = new Action<object,object,object[]>(property.SetValue),
kvp.Value
}
);
foreach (var match in matches)
match.Set(instance, match.Value, null);
}
public static IDictionary<string, object> Serialize<T>(T instance)
{
var props = typeof(T).GetProperties();
var ret = new Dictionary<string, object>();
foreach (var property in props)
{
if (!property.CanWrite || !property.CanRead)
continue;
ret.Add(property.Name, property.GetValue(instance, null));
}
return ret;
}
}
public class Program
{
public static void Main()
{
var nss = new NonSerializableSheep
{
Name = "Dolly",
Id = 12
};
Console.WriteLine(nss);
var bag = GhettoSerializer.Serialize(nss);
// a factory deserializer eliminates the additional
// declarative step
var nssCopy = new NonSerializableSheep();
GhettoSerializer.Initialize(nssCopy, bag);
Console.WriteLine(nssCopy);
Console.ReadLine();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you find which database a table is located in, of which you know the name (e.g. dbo.mytable1), in Microsoft SQL Server Management Studio 2005? I know the name of the table I want to find. I'm using Microsoft SQL Server Management Studio 2005, and I want to search all databases in the database server that I'm attached to in the studio. Is this possible? Do I need to query the system tables?
A: You can use the sp_MSforeacheachdb.
sp_MSforeachdb 'IF EXISTS(SELECT * FROM sys.tables WHERE [Name] = ''TableName'') PRINT ''?''';
A: As above but use system function not system tables
EXEC sp_MSForEachDB 'USE [?] IF OBJECT_ID(''dbo.mytable'') IS NOT NULL PRINT ''?'''
A: use master
DECLARE @db_name varchar(128)
DECLARE @DbID int
DECLARE @sql_string nvarchar(4000)
DECLARE @TableName varchar(30)
Select @TableName = ''
set nocount on
CREATE TABLE [#tblDatabaseName] (
[DbName] [varchar] (128) NOT NULL ,
[TableName] [varchar] (128) NOT NULL )
declare db_cursor cursor forward_only for
SELECT name, DbID
FROM master..sysdatabases
WHERE name NOT IN ('northwind', 'pubs')
AND (status & 32) <> 32 --loading.
AND (status & 64) <> 64 --pre recovery.
AND (status & 128) <> 128 --recovering.
AND (status & 256) <> 256 --not recovered.
AND (status & 512) <> 512 --Offline
AND (status & 32768) <> 32768 --emergency mode.
AND DbID > 4
open db_cursor
fetch next from db_cursor into @db_name, @DbID
while @@FETCH_STATUS = 0
begin
set @sql_string = ''
+' Insert into #tblDatabaseName '
+' select ''' + @db_name + ''' as ''DbName'', '
+' o.name as ''TableName'' '
+' from [' + @db_name + ']..sysobjects o with(nolock) '
+' where o.name like ''' + @TableName + ''' '
execute sp_executesql @sql_string
fetch next from db_cursor into @db_name, @DbID
end
deallocate db_cursor
select * from #tblDatabaseName
drop table #tblDatabaseName
A: sp_MSForEachDB is an undocumented proc that could do this for you. Getting the output out is a little harder so I'll leave that for you.
EXEC sp_MSForEachDB 'USE [?] IF EXISTS(SELECT * FROM Sys.Objects WHERE Type = ''U'' AND Name = ''Product'') PRINT ''?'''
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Beginner: Fastest way to cast/copy byte() into single() I've got a byte() array returned as result of directx sound capture, but for other parts of my program I want to treat the results as single(). Is trundling down the array item by item the fastest way of doing it or is there a clever way to do it ?
The code that gets it is
CType(Me._applicationBuffer.Read(Me._nextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())
which creates the byte array, can Ctype handle single ? (note, I can't figure out a way to do it!)
A: public float[] ByteArrayToFloatArray(byte[] byteArray)
{
float[] floatArray = new float[byteArray.Length / 4];
for (int i = 0; i < floatArray.Length; i++)
{
floatArray[i] = BitConverter.ToSingle(byteArray, i * 4);
}
return floatArray;
}
The fastest way to do this (in terms of performance as opposed to how long it takes to write) would probably be to use the CopyMemory API call.
A: Try
float f = BitConverter.ToSingle(bytearray, 0);
In VB (I think):
Dim single s;
s = BitConverter.ToSingle(bytearray, 0);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Robot simulation environments I would like to make a list of remarkable robot simulation environments including advantages and disadvantages of them. Some examples I know of are Webots and Player/Stage.
A: ROS will visualize your robot and any data you've recorded from it.
Packages to check out would rviz and nav_view
A: This made me remember the breve project.
breve is a free, open-source software package which makes it easy to build 3D simulations of multi-agent systems and artificial life.
There is also a wikipage listing Robotics simulators
A: Microsoft Robotics Studio/Microsoft Robotics Developer Studio 2008
Also read this article on MSDN Magazine
A: It all depends on what you want to do with the simulation.
I do legged robot simulation, I am coming from a perspective that is different than mobile robotics, but...
If you are interested in dynamics, then the one of the oldest but most difficult to use is sd/fast. The company that originally made it was acquired by a large cad outfit.
You might try heading to : http://www.sdfast.com/
It will cost you a bit of money, but I trust the accuracy of the simulation. There is no contact or collision model, so you have to roll you own. I have used it to simulate bipeds, swimming fish, etc.. There is also no visualization. So, it is for the hardcore programmer. However, it is well respected among us old folk.
OpenDynamics engine is used by people http://www.ode.org/ for "easier" simulation. It comes with an integrator and a primitive visualization package. There are python binding (Hurray for python!).
The build in friction model.. is ... well not very well documented. And did not make sense. Also, the simulations can suddenly "fly apart" for no apparent reason. The simulations may or may not be accurate.
Now, MapleSoft (in beautiful Waterloo Canada) has come out with maplesim. It will set you back a bit of money but here is what I like about it:
It goes beyond just robotics. You can virtually anything. I am sure you can simulate the suspension system on a car, gears, engines... I think it even interfaces with electrical circuit simulation. So, if you are building a high performance product, than MapleSim is a strong contender. Goto www.maplesoft.com and search for it.
They are pretty nice about giving you an eval copy for 30 days.
Of course, you can go home brew. You can solve the Lagrange-Euler equations of motion for most simple robots using a symbolic computation program like maple or mathematica.
EDIT: Have not be able to elegantly do certain derivatives in Maple. I have to resort to a hack.
However, be aware of speed issue.
Finally for more biologically motivated work, you might want to look at opensim (not to be confused with OpenSimulator).
EDIT: OpenSim shares a team member with SD/Fast.
There a lots of other specialized simulators. But, beware.
In sum here are the evaluation criteria for a simulator for robot oriented work:
(1) What kind of collision model do you have ? If it is a very stiff elastic collision, you may have problem in numerical stability during collisions
(2) Visualization- Can you add different terrains, etc..
(3) Handy graphical building tools so you don't have to code then see-what-you-get.
Handling complex system (say a full scale humanoid) is hard to think about in your head.
(4) What is the complexity of the underlying simulation algorithm. If it is O(N) then that is great. But it could be O(N^4) as would be the case for a straight Lagrange-Euler derivation... then your system just will not scale no matter how fast your machine.
(5) How accurate is it and do you care?
(6) Does it help you integrate sensors. For mobile robots you need to have a "robot-eyes view"
(7) If it does visualization, can it you do things like automatically follow the object as it is moving or do you have to chase it around?
Hope that helps!
A: It's not as impressive looking as Webots, but RobotBasic is free, easy to learn, and useful for prototyping simple robot movement algorithms. You can also program a BasicStamp from the IDE.
A: I've been programming against SimSpark. It's the open-source simulation engine behind the RoboCup 3D Simulated Soccer League.
It's extensible for different simulations. You can plug in your own sensors, actuators and models using C++, Ruby and/or RSG (Ruby Scene Graph) files.
A: ABB has a quite a solution called RobotStudio for simulating their huge industrial robots. I don't think it's free and I don't guess you'll get much fun out of it but it's quite impressive. Here's a page about it
A: I have been working with Carmen http://carmen.sourceforge.net/ and find it useful.
One of the disadvantages with Carmen is the documentation with all respect I think the webpage is a bit outdated and insufficient. So I like to hear from other people with experience in working with Carmen, or student reports/projects dealing with Carmen.
A: You can find a great list with simulation environments http://www.intorobotics.com/robotics-simulation-softwares-with-3d-modeling-and-programming-support/
MRDS is one of the best and it's free. Also LabView is good to be used in robotcs
A: National Instruments' LabView is a graphical programming environment for developing measurement, test, and control systems.
It could be used for 3D control simulation with SolidWorks.
A: MRDS is free and is one of the best simulation environment for robotics. Workspace also can be used, and please check this link if you want a complete list with robotics simulation software
A: Trik Studio has a nice and clear 2D model simulator and also visual and textual programming programming environments for them. They also soon will support 3D modeling tools based on Morse simulator. Also it is free and opensource and has multi-language interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Best Linux distribution for running Mono I'm a .Net developer and would like to investigate building and running our framework on Mono.
If the initial project is successful I will happily invest in an OS learning curve, but right now I want to focus on getting things up and running and seeing the code working.
What would be the best distribution to start with, assuming that I know very little about Linux, but am an experienced developer? How quickly (hours/days/weeks?) can I expect to achieve this?
Some Feedback so far (Thanks for the answers, guys):
Decided on CentOS, but this was also because this fits in with a particular implementation of the .Net code that I want to port to Mono.The only issue was that I needed to go to version 4 for an out-the-box install of Mono
With some assistance I have been able to get this to a point where I am able to run compiles and start addressing the porting issues. This took a few hours - biggest learning curve is around driving Linux.
20081231: Found the following article for running mono on ubuntu: http://www.ddj.com/windows/212201484
A: The Mono download page gives a fairly big hint as to their preferred distros:
http://www.go-mono.com/mono-downloads/download.html
There's also a page for 'Unsupported distros':
http://www.mono-project.com/Other_Downloads
A: Probably Novell (SuSE), since they fund the mono project and pay the core developers, odds are they're using Novell workstations for their initial coding.
It really shouldn't matter much, though.
A: To get started as quickly as possible, there is a VMWare image available on Mono's Download page. It comes with Mono and all its tools pre-installed, including a running ASP.Net server. You can start with this, and then migrate to whichever distro you choose if you go forward.
A: I work for Novell, so I am going to recommend OpenSUSE as the distribution to use for Mono of course.
When you use OpenSUSE, not only you get Mono, but there are hundreds of open source libraries and .NET based applications that we have ported and make available through our update system.
Additionally, many of the preview features are available as packages that are ready to install on OpenSUSE. Other distributions tend to lag behind in both of the above areas.
Besides, the more OpenSUSE out there, the more funds that we get to continue to improve Mono.
A: If you are a linux beginner I would start with Ubuntu Linux Server;
I installed Mono on a Gentoo server a couple of weeks ago, just to find out that it can't run precompiled ASP.net sites :') You be warned, Linux ain't made for .NET. You should be able to set up the server in a day or 2, configuring Mono to work might take some time...
A: Use Linux MINT - one of the most complete distros. Also, it has great package management and great startup configuration.
A: It's integrated well with suse. But also works great on Ubuntu and ubuntu seems to appeal more to linux newcomers.
A: Like others have said, Novell has direct ties to Mono, but I wouldn't think the mono experience would vary a great deal amongst the bigger names (Suse, Ubuntu, Redhat...).
Are you more interested in getting something that's easy to get up and running or is there a plan to deploy this in production at some point down the road? If it's the former, my personal preference would be Ubuntu, but if it's the latter, then that's more of a question for you and which one will integrate better with your existing infrastructure, and provide the kind of support you're looking for, etc.
A: If you want to avoid the OS-learning curve go for one of the desktop-oriented distributions like Ubuntu or Fedora. Any one of the "big" ones does have mono packages. If you want to try out specific (especially development-) versions, you'll have to do a manual install anyways.
Also avoid running it on real hardware :-) VirtualBox is a great and free virtualisation solution and can really take the hassle out of testing software, if you don't care about dual boot, master boot records and hardware failures.
A: I've been using Ubuntu for Mono development for a while now, and I've found it perfectly satisfactory, execept that it's a little tough to set up Apache with mod_xsp to get the web portion working. The GTK# in MonoDevelop with a Stetic UI is fine though.
A: As far for running mono, in my case for ASP.NET, I've a preference over arch linux (very popular rolling release distro, the one I use on my desktops) for development test server and ubuntu (or fedora) for production.
I've started using linux on Set/2010 as my main desktop solution and as senior .NET developer right know I' feeling very comfortable on it, I'me not an expert but I already manage the majority of the required tasks to do the job using my own skills (and a lot of Googling :D).
At the same time, concerning development, i still use a Windows 7 VM to run the best ever IDE for it VS2010. MonoDevelop is getting cooler but is very unstable an lack a lot of features for web development.
Learning about a new OS is good. I should use what best fit to do the job: linux, windows, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Should I have a dedicated primary key field? I'm designing a small SQL database to be used by a web application.
Let's say a particular table has a Name field for which no two rows will be allowed to have the same value. However, users will be able to change the Name field at any time.
The primary key from this table will be used as a foreign key in other tables. So if the Name field was used as the primary key, any changes would need to be propagated to those other tables. On the other hand, the uniqueness requirement would be handled automatically.
My instinct would be to add an integer field to act as the primary key, which could be automatically populated by the database. Is there any point in having this field or would it be a waste of time?
A: Though it's faster to search and join on an integer column (as many have pointed out), it's even faster to never join in the first place. By storing a natural key, you can often eliminate the need for a join.
For a smallish database, the CASCADE updates to the foreign key references wouldn't have much performance impact, unless they were changing extremely often.
That being said, you should probably use an integer or GUID as a surrogate key in this case. An updateable-by-design primary key isn't the best idea, and unless your application has a very compelling business reason to be unique by name - you will inevitably have conflicts.
A: I would use a generated PK myself, just for the reasons you mentioned. Also, indexing and comparing by integer is faster than comparing by strings. You can put a unique index on the name field too without making it a primary key.
A: Yes - and as a rule of thumb, always, for every table.
You should definitely not use a changeable field as a primary key and in the vast majority of circumstances you don't want to use a field that has any other purpose as a primary key.
This is basic good practice for db schemas.
A: Have an integer primary key is always a good thing from the performance prospective. All of your relationships will be much more efficient with an integer primary key. For example, JOINs will be very much faster (SQL Server).
It will also allow you future modifications of the database. Quite often you have a unique name column only to find out later that the name it is not unique at all.
Right now, you could enforce the uniqueness of the column Name by having an index on it as well.
A: I would use an auto-generated ID field for the primary key. It's easier to join with tables based off integer IDs than text. Also, if field Name is updated often, if it were a primary key, the database would be put under stress for updating the index on that field much more often.
If field Name is always unique, you should still mark it as unique in the database. However, often there will be a possibility (maybe not currently but possibly in the future in your case) of two same names, so I do not recommend it.
Another advantage for using IDs is in the case you have a reporting need on your database. If you have a report you want for a given set of names, the ID filter on the report would stay consistent even when the names might change.
A: What you are describing is called a surrogate key. See the Wikipedia article for the long answer.
A: If you're living in the rarefied circles of theoretical mathematicians (like C. Date does in the-land-where-there-are-no-nulls, because all data values are known and correct), then primary keys can be built from the components of the data that identify the idealized platonic entity to which you are referring (i.e. name+birthday+place of birth+parent's names), but in the messy real world "synthetic keys" that can identify your real-world entities within the context of your database are a much more practical way to do things. (And nullable fields can be very useful to. Take that, relational-design-theory people!)
A: The primary key for a record must be unique and permanent. If a record naturally has a simple key which fulfills both of those, then use it. However, they don't come around very often. For a person record, the person's name is neither unique nor permanent, so you pretty much have to use a auto-increment.
The one place where natural keys do work is on a code table, for example, a table mapping a status value to its description. There is little sense to give "Active" a primary key of 1, "Delay" a primary key of 2, etc. When it is just as easy to give "Active" a primary key of "ACT"; "Delayed", "DLY"; "On Hold", "HLD" and so on.
Note also, some say you should use integers over strings because they compare faster. Not really true. A comparing two 4-byte character fields will take exactly as long as comparing two 4-byte integer fields. Longer string will, of course take longer, but if you keep the codes short, there's no difference.
A: If your name column will be changing it isn't really a good candidate for a primary key. A primary key should define a unique row of a table. If it can be changed it's not really doing that. Without knowing more specifics about your system I can't say, but this might be a good time for a surrogate key.
I'll also add this in hopes of dispelling the myths of using auto-incrementing integers for all of your primary keys. It is NOT always a performance gain to use them. In fact, quite often it's the exact opposite. If you have an auto-incrementing column that means that every INSERT in the system now has that added overhead of generating a new value.
Also, as Mark points out, with surrogate IDs on all of your tables if you have a chain of tables that are related, to get from one to another you might have to join all of those tables together to traverse them. With natural primary keys that is usually not the case. Joining 6 tables with integers is going to usually be slower than joining 2 tables with a string.
You also often loose the ability to do set-based operations when you have auto-incrementing IDs on all of your tables. Instead of insert 1000 rows into a parent table, then inserting 5000 rows into a child table, you now have to insert the parent rows one at a time in a cursor or some other loop just to get the generated IDs so that you can assign them to the related children. I've seen a 30 second process turned into a 20 minute process because someone insisted on using auto-incrementing IDs on all of the tables in a database.
Finally (at least for reasons I'm listing here - there are certainly others), using auto-incrementing IDs on all of your tables promotes poor design. When the designer no longer has to think about what a natural key might be for a table it usually results in erroneous duplicates ending up in the data. You can try to avoid the problem with unique indexes, but in my experience developers and designers don't go through that extra effort and after a year of using their new system they find that the data is a mess because the database didn't have proper constraints on the data through natural keys.
There's certainly a time for using surrogate keys, but using them blindly on all tables is almost always a mistake.
A: The primary key must be unique for every row. The auto_increment Integer is very good idea, and if you don't have other ideas about populating the primary key then this is the best way.
A: In addition to what is all said, consider using a UUID as PK. It will allow you to create keys that are uniq spanning multiple databases.
If you ever need to export/merge data with other database, then the data will always stay unique and relationships can be easily maintained.
A: Inevitably, a few truths:
1: You will definatly have duplicate names
2: There will definatly be names that change
I would never consider a name to be a primary key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: C# compiler number literals Does anyone know the full list of C# compiler number literal modifiers?
By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this...
var x = 0; // x is Int32
var y = 0f; // y is Single
What are the other modifiers I can use? Is there one for forcing to Double, Decimal, UInt32? I tried googling for this but could not find anything. Maybe my terminology is wrong and so that explains why I am coming up blank. Any help much appreciated.
A: var y = 0f; // y is single
var z = 0d; // z is double
var r = 0m; // r is decimal
var i = 0U; // i is unsigned int
var j = 0L; // j is long (note capital L for clarity)
var k = 0UL; // k is unsigned long (note capital L for clarity)
From the C# specification 2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by Jon Skeet.
A: You might want to start by looking at the C# language spec. Most of the types are listed in there, and have a suffix:
*
*L = long
*F = float
*U = uint
*ulong's are a little different
*m = decimal (money)
*D = double
Of course, if you stop using var then you get around the whole problem, and your code becomes more readable (ok, thats subjective, but for something like this, it's more readable by other people:
var x = 0; //whats x?
float x = 0; //oh, it's a float
byte x = 0; // or not!
A: If you don't want to have to remember them, then the compiler also accepts a cast for the same purpose (you can check the IL that the effect is the same - i.e. the compiler, not the runtime, does the cast). To borrow the earlier example:
var y = (float)0; // y is single
var z = (double)0; // z is double
var r = (decimal)0; // r is decimal
var i = (uint)0; // i is unsigned int
var j = (long)0; // j is long
var k = (ulong)0; // k is unsigned long
And for the record, I agree that "var" is a bad choice here; I'll happily use var for a SortedDictionary<SomeLongType, SomeOtherLongType>, but for "int" it is just lazy...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: Why must endpoints manage conversions between bytes sent and received TSNs sent and received in SCTP congestion control? As stated in RFC 3286:
"...endpoints must manage the conversion between bytes sent and received and TSNs sent and received, since TSN is per chunk rather than per byte".
How does this affect the congestion control algorithm?
A: There are two reasons:
1. Pragmatically, RFC 3286 refers RFC 2581 for most of the congestion control, and it works in bytes.
2. Practically, and this is a stronger reason, there needs to be a buffer assigned at each end and these would be hard to define in terms of TSNs (chunks) since these are variably size. This would either mean over-allocating space in the buffer e.g. 64K * TSNs, or using a dynamically allocated list. The former is wasteful of space, the latter relatively slow.
Does this answer your question, or was it more related to your last question?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compare view with stream I use ClearCase. I have a snapshot view. Is there a way to compare this view with stream to find changed files?
In TortoiseSVN this is called "Check for modifications" and shows all difference between local copy and what we have in the repo.
A: I'm not sure about Clear Case's own possibilities, but you always can make a view of that stream and compare your original view with created one using any file/folder comparison tool. I use Araxis Merge for that. There is also an open source tool: WinMerge
A: Have you tried the 'version-tree' feature?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using sIFR in nyroModal lightbox I'm using sIFR in a page that's being popped up in a nyroModal lightbox, but when the page is displayed, the sIFR objects aren't being shown. What do I need to do to get them to show?
A: The idea will be to use the endShowContent callback from nyroModal to sIFR your text.
$.fn.nyroModal.settings.endShowContent = function(elts, settings) {
$('YOUR SELECTOR', elts.content).media(function(el, options) {
// What you need to do
});
};
Hope it will help.
If you still have some trouble, come on the google code page to post your issue: http://code.google.com/p/nyromodal/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update Firefox 2 compatible extensions using IFRAME to Firefox 3? I am trying to update a custom firefox extension that I created for some tasks at work. Basically it is a sidebar that pulls up one of our webpages in an iframe for various purposes. When moving to Firefox 3 the iframe won't appear at all.
Below is an example of the XUL files that contains extension specific code including iframe, currently with just an attempt to load google but it it won't work with anything. I can't find any mention online of changes in FF3 that would cause this. Any suggestions would be appreciated.
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://customsidebar/skin/customsidebar.css" type="text/css"?>
<overlay id="customsidebar-Main" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript" src="chrome://customsidebar/content/customsidebar.js"/>
<vbox flex="1">
<toolbar>
<vbox>
<hbox id="customsidebar_TopToolbarRow">
<toolbarbutton label="Refresh" id="customsidebar_Refresh" oncommand="customsidebar_Refresh()" />
</hbox>
<hbox>
<label control="customsidebar_StatusBox" value="Log"/>
<textbox id="customsidebar_StatusBox" multiline="true" rows="1" wrap="off" />
</hbox>
</vbox>
</toolbar>
<iframe id="customsidebar_Iframe" src="http://www.google.com" />
</vbox>
</overlay>
Here is the overlay XUL file
<?xml version="1.0"?>
<overlay id="CustomSidebar-Overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<menupopup id="viewSidebarMenu">
<menuitem observes="viewCustomSidebar" />
</menupopup>
<broadcasterset id="mainBroadcasterSet">
<broadcaster id="viewCustomSidebar"
autoCheck="false"
label="CustomSidebar"
type="checkbox" group="sidebar"
sidebarurl="chrome://customersidebar/content/customersidebarMain.xul"
sidebartitle="CustomSidebar"
oncommand="toggleSidebar('viewCustomSidebar');"/>
</broadcasterset>
</overlay>
A: *
*Set flex="1" on the iframe
*The XUL code for sidebar is not an overlay, it's a document loaded inside an iframe (look at the Firefox main window in the DOM inspector). So the root element should be <page>, not <overlay>. This, combined with the flex="1", should make the page display.
*You usually want to put type="content" or type="content-primary" on the iframe. Definitely so if you load untrusted pages in it.
A: I would try setting flex="1" on the iframe. If that's not working, perhaps try it with the browser element instead of iframe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you manage .vcproj files in source control which are changed by multiple developers? We use Subversion as our source control system and store the VisualStudio project files (vcproj) in the source control system as is normal I think. With Subversion we don't use any form of file locking, so if two developers are working on the same project at the same time and both add files to the project, or change settings, the second one to commit has to merge the changes.
How do you merge these changes?
The vcproj files are just text files so it is possible to edit them by hand but they are not very amenable to hand editing, especially by junior developers.
The ways I can think of are
*
*Get the latest version from svn and re-add all local changes manually
*Edit the file by hand to resolve any conflicts from an automatic merge
*Implement some form of locking scheme to prevent simultaneous changes
*Have an agreement between developers so they do not make simultaneous changes
Currently we are using the first option of re-adding all changes manually but this is time consuming and I was wondering if there is a better way.
With source files the automatic merge feature works most of the time and we don't get many conflicts.
A: I've found that option 2 (edit the files by hand) generally works fairly well, as long as you're using a good diff tool (I use WinMerge). The main problem I've run into is that Visual Studio will sometimes reorder the file. But, if you have a good diff/merge tool then it should be able to differentiate between changed content and moved content. That can help a lot.
A: You might find Project: Merge or Tools for SLN file useful
A: This is a tough problem and I think a weakness in the Visual Studio architecture. The way we found round it was to not have the proj files in source control at all and to have a build script that handled the configuration settings.
The alternative was very messy and we could not guarantee consistent builds or environments between developers. This led to a huge number of downstream integration problems and eventually we took the draconian step of removing the project files from source control.
The developers environments could still become misaligned but it showed up when they tried to build things themselves.
A: Using TFS here, but I don't think it makes a difference.
We also don't lock, and sometimes have to deal with merging project files. I've never found it to be that complex or much of an issue. Rarely do we ever experience issues that can't be merged automatically, and the manual merge process is pretty much trivial.
There's only one caveat to this: Check in often! If you make major changes to the project structure and don't check them in immediately those changes can start compounding the complexity of later merges. If I make a major change to the structure of a project, I usually give everybody a heads up. I'll ask them all to check in their current work, and then take care of the merge myself.
A: I found this recently: http://www.codeproject.com/KB/macros/vcproj_formatter.aspx
If you run this tool on a vcproj file and on a modified version of it then you can merge them together easily with your favorite text merge tool, and in addition the result is a more compact pretty vcproj file.
A: Options 1 and 2 are not mutually exclusive - if the developer is junior level, let them use option 1 (re-get the project file and re-do the changes) if that's more comfortable for them. For more senior developers, option 2 (merge using a merge tool) is perfectly fine.
I think this is a situation that currently has no magic bullet - sometimes merging is a pain.
A: We use a diff tool (WinMerge) to merge changes. The project files are (for the most part) really straight-forward XML. The key here, though, is that there never should be any surprises when merging, because good communication is part of the bed-rock of effective source control.
Simultaneous changes to the project are perfectly fine as long as people communicate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Windows Form Designer: Could not load file or assembly Has anyone ever had the issue where trying to "View Designer" on a windows form in Visual Studio .NET causes the error: "Could not load file or assembly…" ?
In this case, the assembly in question was XYZ.dll. I managed to fix this by adding XYZ.dll and all its references to my project's references (even though my project doesn't directly depend on them) and rebuilding the whole solution. However, after that, I removed all those references from my project, rebuilt, and it still worked.
One other piece of information is that I use Resharper 2.5. Someone else pointed out that it might be Resharper doing some shadow copying. I'll look into this next time this happens.
Does anyone have a understanding of why this error happens in the first place, and possibly the 'correct' way to fix it?
A: Using VS 2005, I ran into this same problem. I performed the steps Chien listed in his original question, but it still didn't work until I closed VS and reopened the solution. Now the Designer view looks fine.
A: We have same problem. Some Form/UserControl classes can not be viewed in designer and Visual Studio causes various exceptions.
There are one typical cause:
One of designed component thrown unhandled exception during initialization ( in constructor or in Load event or before ).
Not only for this case, you can run another instance of visual studio, open/create some independent project, go to menu -> Debug -> Attach to process ... -> select instance of devenv.exe process with problematic designer. Then press Ctrl+Alt+E, the "Exceptions" windows should be shown. There check "Thrown" in categories of exception.
Now active the visual studio with designer and try view designer. If the exception will be thrown, you will see callstack ( and maybe source code, if the exception was thrown from your code ) and other typical information about thrown exception. This information may be very helpful.
If you have something like TypeLoadException from Winforms designer, when debugging Visual Studio (devenv.exe process) with another instance of Visual Studio, have a look at the Debug > Modules panel to see exactly which version of your DLL is loaded. Turned out that it was an unexpected version for us, hence the issue.
A: I guess this problem occurs for different reasons, but I thought I'd share my case anyway. I hope someone will find a clue to what's going on with their project.
My problem occured since Visual Studio (C# project) couldn't find the managed c++ dll and copy it to the location mentioned in J Collins post => the designer couldn't find the file. I noticed it wasn't copied there with the other DLL:s and found out that it had a different/non-standard output directory. Changing this to the standard made Visual Studio perform the copy.
A: This is an old question that still appears to have no answer, either here or in the wider forum pool, most advice relates to relentless clean>rebuilds or close>clean folders>reopen or restarting the machine. I don't have a solid answer at present though have done some research into it and thought I might share. Summarily, there is one location into which all designer files are copied when a control or form is designed, another location which old files can exist and a method is described to catch all designer exceptions before the designer can generate the error page.
There appears to be two cases where either an assembly cant be loaded or can't be found. The first is caused by files failing to copy to designer-required locations, the second is outdated files being left behind.
As mentioned above files can fail to copy when a project fails to directly reference all references required by its referenced references and their references, recursively, down to the framework. This can be alleviated by carefully tracking all references and their dependents, ensuring all are accounted for.
The Visual Studio designer uses a specific location to cache dlls for its use in the designer, isolated from the source /bin folders of the projects:
Windows XP:
C:\Documents and Settings\[user_name]\Local Settings\Application Data\Microsoft\VisualStudio\10.0\ProjectAssemblies
Windows 7:
C:\Users\[user_name]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies
In this location, compiled assemblies are copied to dynamically created folders, one folder per assembly. Checking the assembly version dates on this location, it seems to be quite up to date, being deleted when visual studio exits. All assemblies are copied when a designer is viewed with newly compiled files. A new copy of each assembly is made into this location for each designer, so the location may hold multiple identical copies of each assembly.
One other location exists however where assemblies may be copied, and is a part of the assembly search sequence, apparently ahead of the ProjectAssemblies folder and that is in:
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE
I have no knowledge of how or when assemblies get copied to this location, but it is not often so what files do arrive here quickly become a source of outdated references. When a designer failed with the 'Failed to load file or assembly' error, the version sought by the designer was a version only referenced by the assembly at this location.
This was discovered by using a second Visual Studio instance debugging on the first, with all .net symbols loaded, and all known exceptions breaking on throw as opposed to when unhandled. This allowed the second instance to intercept the handled designer exceptions and reveal that file location. This was the resulting output of the designer error that I used:
=== Pre-bind state information ===
LOG: User = **************
LOG: DisplayName = ***********, Version=1.0.4275.22699, Culture=neutral, PublicKeyToken=null
(Fully-specified)
LOG: Appbase = file:///C:/Program Files/Microsoft Visual Studio 10.0/Common7/IDE/
LOG: Initial PrivatePath = NULL
Calling assembly : ***********, Version=1.0.4275.22699, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: The same bind was seen before, and was failed with hr = 0x80070002.
A: It happened to me very frequently on VS2005, specially when adding custom controls to the winform. Usually I just needed to just rebuild, without needing to add extra references, or close and reopen VS.
There is no apparent cause for this, just VS bugs.
A: I had a similar problem.
In my case, I had a base form, which referenced a class in a mixed-mode dll (c++ managed wrapper to unmanaged library).
My derived form did not load correctly, giving the same error described above.
However, the following resolved the issue: http://support.microsoft.com/kb/967050
*
*Build both the mixed-mode project and the ui project for Win32. Since VS is 32 bit, it cannot load x64 unmanaged code:
*Clear the ProjectAssemblies folder (requires shutting down VS first)
When you reopen VS, the designer loads with no issues. Note that by default, C# projects are compiled as Any CPU which compiles to x64 on Windows x64.
Hope this helps someone.
A: Delete ALL bin and obj directories for all the projects in the solution. Also delete the folders in C:\Users<User>\AppData\Local\Microsoft\VisualStudio\9.0\ProjectAssemblies. Use 9.0 for VS2008, 10.0 for VS2010 etc.
A: Was struggling with this issue for a few hours. Here's what I learned: CHECK IF THE DLL THE DESIGNER IS TRYING TO LOAD IS A 64-BIT DLL.
Turns out, well, obvious to me now, VS is a 32-bit application, therefore the VS Designer -- surprise! surprise! is also a 32-bit application so if you have a UserControl or other WinForms control that has a reference to a 64-BIT DLL -- THAT IS A BIG NO-NO which will cause your form not to render in the VS Designer and produce the could-not-load-file-or-assembly error. So the first thing you should do is make sure that the DLL the Designer is complaining about is NOT a 64-bit DLL.
A: I had this problem in a c++/cli project.
As other people have mentioned, apparently the Windows Form Designer instantiates some version of your Form/Usercontrol before rendering it.
If the Form Designer cannot instantiate the class for whatever reason, it will fail. So what I did was comment out the constructor of the offending Usercontrol, and rebuild my project.
This allowed me to use the Form Designer again.
Of course you could use this method to selectively comment out parts of the constructor until identifying the part that makes the Form Designer choke, and if possible fix it.
A: I'm using VS2005 and VS2013 and seen the same problem. Some Visual Studio form designers in my project work and others won't open in design mode. Some opening attempts even crash Visual Studio, before the error page appear, saying:
To prevent possible data loss before loading the designer, the
following errors must be resolved:
An observation:
If there are inherited components in the form, the designer might stop working
A pseudo code example of the observation:
...
using System.Windows.Forms; // UserControl
namespace MyNamespace
{
public class MyForm : Form
{
public MyForm()
{
InitializeComponent();
...
}
private void InitializeComponent()
{
//this.ctrl = new MyNamespace.MyCtrl(); // Inherited class
this.ctrl = new System.Windows.Forms.UserControl();
...
}
//private MyNamespace.MyCtrl myCtrl; // Inherited class
private UserControl ctrl;
}
public class MyCtrl : UserControl
{
...
}
}
In the non-pseudo-code implementation, I commented out the inherited component MyCtrl in MyForm, and instead used the base class UserControl. The Visual Studio Form Designer started working again!How to write a properly Visual Studio Form Designer -interacting, inherited component class in C# is beyond me. But, this observation might be a clue to someone, whom can work it out.
A: I concur with the Resharper comment. I'm running 4.1. I disabled it, restart VS2008, and tried the "Convert to Web Application" again, and it worked.
A: I've seen this happen in VS2005 for Window Forms, ASP.NET, and Compact Framework projects. The project I'm building has a dependency on another assembly in my solution, but complains that it can't load it when trying to generate the designer file.
I'm not sure on the exact cause, but this sometimes will happen after we bump up the version number of the assembly. For some reason Visual Studio won't see this assembly as "new" and won't drop the new version in the current project's bin/ folder. Most of the time it does though.
Deleting the bin/ folder (and the obj/ folder for good measure) of the project with the designer error, and then rebuilding, seems to make the hurt go away.
A: I'v faced with the same problem.
I'v removed the reference from the project and added again, and all works fine (looking in the ptoject file i saw that reference definition was changed, for ex. "SpecificVersion" tag was added and set to the "false").
A: I have found, with problems like this, and many others, the problem tends revolve around the .NET framework installation. Lots of times, like during a system crash, files can become corrupted esp. if you have virtual memory turned off. When files in the C:\WINDOWS\Microsoft.NET folder get corrupted, they don't work the way they should, since there are alot of these files, errors dont always happen. Some parts of a file might be ok and load, then others dont. Over the years I have found keeping a FULL backup of the Microsoft.NET folder in an archive that has some type of corruption protection works well for me. You would not believe the number of things that corrupted .NET files cause to go wrong. Just about every aspect of the IDE depends on parts of it as well as many other features. Of course, if you dont have a backup you should UNINSTALL ALL NET FRAMEWORK INSTALLATIONS (don't repair because this does not guarentee files being rewritten -- the files might pass checksum and length checks but still be corrupt). After uninstalling, reboot the system, ensure that the entire Microsoft.NET folder is deleted, if not, delete it yourself (I had to do this, some files still get left behind). Once this is done, reinstall the NET framework, depending on your OS, you might not be able to get rid of the whole thing. But with windows XP I know you can, i havent tested this on newer OSes youre on your own for that one as far as testing goes. I started out by installing 2.0, then 3.5 SP1, and so on, depending on which Visual Studio you are using. I stick with 2008 because its the fastest for me and still has support for some of the newer stuff like WPF, tr1, etc... hope this helps you an anyone else with .NET woes, the error messages are often misleading but for me 99% of the time it is Microsoft.NET file corruption.
A: To anyone who has this problem in the future and scrolled all the way down searching for it : Delete ComponentModelCache in Appdata/Local/Microsoft/VisualStudio/..
A: I have faced this issue several times. Most of the times clean+rebuild works (sometimes combined with restart of Visual studio).
Two times when clean+rebuild didn't work it was:
Issue #1
In one of the cases that I faced it had to do with C# and VB.NET.
I had several user controls in my Form which was not loading in designer. The user controls were in C#. Most of them were under the same namespace, but few of them had part of the namespace which didn't match in alphabet-case.
For example:
userContorl1 was in myapp.mynamespace1, and
userControl2 was in myapp.myNamespace1
For C# they are different namespaces as C# is case-sensitive. But VB.NET is case-insensitive. The error that I got was when trying to load myapp.mynamespace.userControl2. After struggling for long time, I noticed the namespace in error message and corrected in the user control, making them all same as 'myapp.myNamespace1', and viola designer opened after clean+rebuild.
Issue #2
My Form (which was not opening), had many user controls. One of the control was having a property of enum type. This enum was defined inside a generic class. The designer generated code fo this user control was something like:
myUserControl1.SomeType = somenamespace.SomeGenericClass(of Date).SomeEnum
The error that i got while opening designer, was like:
could not load type
somenamespace.SomeGenericClass[System.Date]+SomeEnum
I moved the enum outside the class and replaced the designer code to:
myUserControl1.SomeType = somenamespace.SomeEnum
And the designer opened. :)
I hope this helps somebody.
A: I will say the responses in this thread helped me somewhat, but didn't exactly nail down what was occurring in my custom user controls.
In my particular case, I have numerous helper class libraries that perform such things as styling on my controls, background logging, and just generic helper classes that perform routine things I do all the time.
I was using some of these other library static methods to perform logging in the case of error. Here's an example:
try
{
_InitializeStuff();
}
catch (Exception ex)
{
Logger.Instance.Log("Couldn't instantiate: " + ex.Messsage);
}
I did this in the Constructor, Load, and Property Set methods of my User Controls ... and the designer couldn't always build it's path to the static method calls, so the designer would fail.
I tried placing DesignMode checks around it, but the problem wasn't at runtime -- it was designtime, and the links couldn't be built. The only option for me was to remove all references to my static helper classes in the following places of my Custom User Controls:
*
*Constructor
*Load
*Property Accessors
Trying to debug this with a secondary IDE and using Attach to Process did not work for me, unfortunately.
A: Also make sure you have a using declaration for the library with the control in your form or control. Once the designer knows about it, it write the full namespace in references to objects in the Form.designer.cs file.
A: I tried many of the suggestions above related to deleting files, rebuliding, restarting, etc. My problem was that it could not load a utility assembly that was used by a few projects in the solution. Another project had common controls. So, Form1 referenced ControlsAssembly1 referenced UtilityAssembly1. The .resx file had properties of types in UtilityAssembly1. I deleted the resources that contained those types. Tried to open the form again (got Null Reference exception because of the missing resource), hit Ignore and Continue and my problem was fixed.
A: In order to get your From back.
First of all go to Visual studio 2008 command prompt.
type devenv /resetsettings
type devenv /resetSkippkgs
*
*In solution explorer click the "Show All files"
*Now Open Form1.vb by double clicking, then click + to expand it.
*Open Form1.Designer.vb
*you can see both tab in you editor window (IDE).
*Now Right Click tab "Form1.vb" and save it
*Similarly Right click the tab Form1.vb [Design] and save it also
*Re-Build your project.
*Restart Visual Studio.
A: I have faced this problem. I did what is said above but it didn't make any sense. Then I added the assembly to the references. Rebuild the project. Closed the Visual Studio. Then reopen the screen and the designer appeared as normal.
Regards,
A: Just to Chime in on this. I build a new version of my UserControl whilst my other project was open and referencing it. When I went back to view the designer in the form referencing the user control, it said it couldn't find the .dll of a specific version.
I tried to remove the reference to the control and from the toolbox, with no luck. The code would compile just fine, but the designer wouldn't show without the error.
Tried all the above and it didn't work.
The .res file for the form has some XML:
<data name="EventBar1.EventCheckedSubscriptions" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAAJoBbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1u
ZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIG1zY29ybGliLCBWZXJzaW9u
PTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUB
AAAANlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkV2ZW50SGFuZGxlcgMA
AAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uAwAAFVN5c3RlbS5FdmVudEhhbmRsZXJbXQgIAgAAAAkDAAAA
AAAAAAAAAAAHAwAAAAABAAAAAAAAAAMTU3lzdGVtLkV2ZW50SGFuZGxlcgs=
</value>
</data>
<data name="EventBar1.EventLengthSubscriptions" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAAJoBbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1u
ZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIG1zY29ybGliLCBWZXJzaW9u
PTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUB
AAAANlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkV2ZW50SGFuZGxlcgMA
AAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uAwAAFVN5c3RlbS5FdmVudEhhbmRsZXJbXQgIAgAAAAkDAAAA
AAAAAAAAAAAHAwAAAAABAAAAAAAAAAMTU3lzdGVtLkV2ZW50SGFuZGxlcgs=
</value>
</data>
<data name="EventBar1.EventLengthTypes" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAAKABY3RybENhbGVuZGFyU2lkZUJhciwgVmVyc2lvbj0xLjAuNzEy
MS4yMTIzNCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsXV0sIG1zY29ybGliLCBW
ZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0
ZTA4OQwDAAAAUWN0cmxDYWxlbmRhclNpZGVCYXIsIFZlcnNpb249MS4wLjcxMjEuMjEyMzQsIEN1bHR1
cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAAT1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5l
cmljLkxpc3RgMVtbY3RybENhbGVuZGFyU2lkZUJhci5FdmVudEJhcitFdmVudExlbmd0aFR5cGUDAAAA
Bl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgQAAC5jdHJsQ2FsZW5kYXJTaWRlQmFyLkV2ZW50QmFyK0V2ZW50
TGVuZ3RoVHlwZVtdAwAAAAgIAgAAAAkEAAAAAAAAAAAAAAAHBAAAAAABAAAAAAAAAAQsY3RybENhbGVu
ZGFyU2lkZUJhci5FdmVudEJhcitFdmVudExlbmd0aFR5cGUDAAAACw==
</value>
</data>
<data name="EventBar1.EventSettingsSubscriptions" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAAJoBbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1u
ZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIG1zY29ybGliLCBWZXJzaW9u
PTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUB
AAAANlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkV2ZW50SGFuZGxlcgMA
AAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uAwAAFVN5c3RlbS5FdmVudEhhbmRsZXJbXQgIAgAAAAkDAAAA
AAAAAAAAAAAHAwAAAAABAAAAAAAAAAMTU3lzdGVtLkV2ZW50SGFuZGxlcgs=
</value>
</data>
I removed this from the .res file and all is well. I did backup the whole folder before I tried this though!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
} |
Q: Java: Newbie-ish inheritance question Suppose I have a base class B, and a derived class D. I wish to have a method foo() within my base class that returns a new object of whatever type the instance is. So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.
Is this possible?
A: As long as each class has a default constructor:
public B instance() throws Exception {
return getClass().newInstance();
}
A: Don't. Make the "foo" method abstract.
abstract class B {
public abstract B foo();
}
Or receive an abstract factory through the base class constructor:
abstract class B {
private final BFactory factory;
protected B(BFactory factory) {
this.factory = factory;
}
public B foo() {
return factory.create();
}
}
interface BFactory {
B create();
}
Add covariant return types and generics to taste.
A: I think this might be possible to do using reflection, i.e. in your superclass you have:
public ClassName getFoo() throws InstantiationException, IllegalAccessException
{
return getClass().newInstance();
}
Where ClassName is the name of your base class.
You'll have to cast it wherever you want to use it though... I'm not sure this is really a great solution!
Edit: newInstance() type methods are usually static, and of course you won't have an idea of what the type of your subclass is with a static method.
I don't think there's any way of getting a static method to (dynamically) create an instance of a subclass.
A: Well, I could be off but I would assume that since "this" always refers to the current object, you could do something like
public B foo() {
return this.getClass().newInstance();
}
or something along those lines? If you create an instance of D and then call d.foo() you should get an instance of D returned as a B. You could return it as a plain Object but you should be as specific as possible in this instance, I think.
A: Apart from the fact that I think there probably is a design flaw if you want to accomplish this, you could try the following approach.
In your question, you are using static (class) methods, B.foo(), D.foo(), this cannot be accomplished using inheritance because the static methods do not have a dynamic nature, they do not take part in the lookup system. So you don't have enough type information.
If you are using a member function foo() you could have the following construct:
public class B {
public B foo()
throws IllegalAccessException, InstantiationException {
return this.getClass().newInstance();
}
}
public class D extends B{
}
public class Test {
public static final void main(String[] args)
{
try {
System.out.println((new B()).foo());
System.out.println((new D()).foo());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
A: As the other answers say, you can use getClass().newInstance() if there is a no-argument constructor in each subclass (make sure to catch InstantiationException and IllegalAccessException).
If any of the constructors require arguments, you can either use reflection or (preferable in my view) define a method like getNewInstance() which you can override in the subclass only if needed.
e.g.
Thing foo() {
Thing th = getNewInstance();
// do some stuff with th
return th;
}
Thing getNewInstance() {
return getClass().newInstance();
}
Then getNewInstance() can be overridden only if you really need to, for subclasses that don't have the default constructor.
Thing getNewInstance() {
return new BigThing(10, ThingSize.METRES);
}
A: @Rik
Well, the real problem is that I have a abstract base class Thing. And Thing has a method called getNextThing() which returns a new instance of Thing.
Then, I have a number of subclasses like BigThing, LittleThing, SomethingThing, and I don't want to keep rewriting the getNextThing() method for each of them. It seems wasteful, since they all do the same... thing.
Am I incorrect in my approach?
A: I'm not sure why you're trying to do what you're actually trying to do. Providing more of a context might let us give you more help.
public class B <X extends B>{
public X foo() throws InstantiationException, IllegalAccessException{
return (X)this.getClass().newInstance();
}
}
public class C extends B<C>{
}
Let me offer you this piece of advice. The way CS classes tend to be taught is that professors are enamored with inheritance, but haven't figured out composition. I think What you might be looking for is composition. So instead of calling getNextThing on the Thing itself, maybe you should think about making Thing implement Iterable
This means you will just need to write an Iterator that can encapsulate the logic of getting the next thing, as it doesn't seem to fit into your inheritance model. Another advantage of this is that you get some nice syntactic devices out of this (enhanced for loop comprehension).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why is "The referenced component 'X' could not be found." considered a warning? I wonder, why the hell... did the VS team consider that NOT finding a project reference as a non crucial thing?
The referenced component 'X' could not be found. should be considered an error... and nothing else.
Is there a way (without turning 'Treat all warnings as errors' on) to get this warning as an error in VS2008?
A: That warning comes from the project system, not the compiler. The project system doesn't know whether or not the reference will actually be needed when the code is compiled. I've run into several cases (all involving multiple platforms and conditional compilation) where this features allows you to maintain a single project file when you might otherwise have to split into one file per configuration.
There is an option to "treat warnings as errors" -- you should be able to find it in the project configuration screen.
A: Why do you think it should be any error? If you had actually used anything in the assembly, then you'd get an error where you use it. So far, all you've said is "I may need this file", and VS is responding "Well, I hope you don't, because I can't find it".
A: This warning does my head in.
I have a project with six configurations - each configuration uses a different version of a particular referenced DLL, and so the references are conditional (by hacking the project file, as I cannot find a way to do it through the VS GUI).
The five references that are not used for the current configuration, despite being present on disk, are always displayed with an exclamation mark in the GUI, and this warning (which does not appear to have a warning ID) is displayed.
I would love to be able to "fix" Visual Studio so that it could determine that due to the configuration currently being built, it is irrelevant that this reference may or may not be present (even though it is present).
Seriously, sometimes Microsoft's obtuseness drives me up the wall.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Separating Demo data in Live system If we put aside the rights and wrongs of putting demo data into a live system for a minute (that's a whole separate discussion!), we are being asked to store some demo data in our live system so that it can be credibly demonstrated without the appearance of smoke + mirrors (we want to use the same login page for example)
Since I'm sure this is a challenge many other people must have - I'd be interested to know what approaches have people have devised to separating this data so that it doesn't get in the way of day to day operations on their systems?
As I alluded to above, I'm aware that this probably isn't best practice. :-)
A: Can you instead, segregate the data into a new database, and just redirect your connection strings (they're not hard-coded, right? right?) to point to the demo database. This way, live data isn't tainted, and your code looks identical. We actually do a three tier-deployment system this way, where we do local development, deploy to QC environments that have snapshots of the live data every few months, and then deploy to live when testing is complete.
A: FWIW, we're looking at using Oracle's row level security / virtual private database feature to seperate the demo data from the rest.
A: I've often seen it on certain types of live systems.
For example, point of sale systems in a supermarket: cashiers are trained on the production point of sale terminals.
The key is to carefully identify the test or training data. I wouldn't say that there's any explicit best practice for how to model this in a database - it's going to be applicaiton specific.
You really have to carefully define the scope of what is covered by the test/training scenarios. For example, you don't want the training/test transactions to appear in production reports (but you may want to be able to create reports with this data for training/test purposes).
A: Completely disagree with Joe. Oracle has a tool to do this regardless of implementation. Before I read your answer I was going to say VPD... But that could have an impact on Production.
Remember Every table in a query changes from
SELECT * FROM tableA
to
SELECT * FROM (SELECT * FROM tableA WHERE Data_quality = 'PROD' <or however you do it>
Every table with a policy that is...
So assuming your test data has to span EVERY table, every table will have to have a policy and every table will be filtered before a SQL can begin working.
You can even hide that column from the users. You'll need to write the policy with some deftness if you do. You'll have to create that value based on how the data is inserted and expose the column to certain admin accounts for maintenance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XML add hyperlink I have a xml blob that's checked against a schema in sql 2005. My website uses xsl to transform and display the blob. How do I add a hyperlink to the xml (in any node) without the sql 2005 schema complaining a node was found in the wrong place? Or the xsl thinking that the hyperlink is a valid xml node?
thank you
A: I'm guessing you aren't encoding the < and > characters correctly. You need to use < and >
A: For more advanced html building, you may need to use the xsl:element tag:
<xsl:element name="a">
<xsl:attribute name="href">http://www.stackoverflow.com</xsl:attribute>
Click here
</xsl:element>
renders
<a href="http://www.stackoverflow.com">Click here</a>
The nice thing about this is that the values for any of the "name" attributes or inner text can be computed xsl values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Architecture for easy update of application I have a system in place which applies calculations to a set of numbers (the specifics aren't really relevant). There are a number of sets of calculations which can be applied by the system users and new sets are added frequently. Currently when a new set of calculations need to be added to the system they are added in to the code base and a new version of the system released. I'd like to be able to add new calculation sets into the system without having to release a whole new version and also to have these new calculations become visible to system users automatically. Currently a new function is created for each set of calculations and a record containing the appropriate function name is added to a system table. These records are visible to system users (function names are aliased of course!) who then select them from a list. The system uses the Eval() function to run the appropriate calculations.
This is a VB6/Access app that I inherited and am currently re-writing in VB.NET and SQL Server.
Does anyone have any advice on how best to do this?
A: Since you're redoing it in .Net, just put the calculations in plugins. Use reflection to load and examine these assemblies at runtime and present the user with functions.
Divil has a good (but fairly old now) article on writing plugin based applications. It will help you out: http://divil.co.uk/net/articles/plugins/plugins.asp (+ it's in VB.Net)
If you do it this way, all you have to do is drop a dll into the right directory and it just works.
A: If you are using a standard set of mathematical functions you can use use allow the user to write their own mathematical functions in a textbox.
Then use a grammar parser such as :TinyPG on CodeProject
With this you can then break down the expression into :Reverse Polish Notation
This can then be easily stored and recalled from the database in a varchar field.
Once this is setup you won't need to republish the application unless you need to add new mathematical functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to wait on another process's status in .NET? I'm working on an integration testing project in .NET. The testing framework executable starts a service and then needs to wait for the service to complete an operation.
What is the best approach for the exe to wait on the service to complete its task (the service itself will not exit upon task completion)?
Both processes have access to the same database, so my first thought was a simple table that records the service's status. Once it's signaled that it's done, the exe can stop waiting and complete its task. Other approaches?
Let me reiterate that the service, once it has completed its task, will remain in a running/in-memory state, so waiting for it to exit won't work. ;-)
Also, this is purely for integration testing purposes, and will never go into production, so "simple" is the operative word.
A: You can pass a Semaphore name to the service on the command line (or via some other mechanism, like hard coding), and then wait on the service to Release() it, by calling WaitOne() in your exe.
App code:
Semaphore s = new Semaphore(1, 1, "MyNamedSemaphore");
// start service, passing the string "MyNamedSemaphore"
s.WaitOne(); // will wait for Release() in service
Service code:
// perform the initial task
// find semaphore name (i.e. from Environment.CommandLine)
Semaphore s = new Semaphore(1, 1, semaphoreName); // will use existing kernel object
s.Release(); // WaitOne in exe will complete
A: WMI calls should give you what you need. You can catch started/finished events and do what you need to from there. (Thanks to Chris Lively for showing me this)
http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx
Alternatively you can use System.Diagnostics.Processes namespace to query for one particular active process, and loop until the process is killed.
A: Can you modify the service code?
If so, use a kernel Event object - the service can create one, your app can wait for it to be signalled, and the service can signal it when its finished. You'll have to give the event a name for it to be used cross-process but that's about as simple as it gets. The service can even continue to run with the event code present, no-one will notice unless they try to create an event with the same name. (or, your testapp could create the event, the service can then try to open it, depending which one is started first. If it succeeds, it can performs its triggering, otherwise it works as usual).
Hint: you want a auto-reset event which 'flips' its state back immediately its triggered all waiting threads.
I'm not sure of the .NET routines, but you want the Win32 CreateEvent, SetEvent, and WaitForSingleObject.
A: You could use IPC Channels: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6143016.html
Or maybe two way remoting: http://www.codeproject.com/KB/IP/TwoWayRemoting.aspx
The database route would be simple, but not necessarily the best.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C# preg_replace? What is the PHP preg_replace in C#?
I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").
$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';
$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
A: Real men use regular expressions, but here is an extension method that adds it to String if you wanted it:
public static class ExtensionMethods
{
public static String PregReplace(this String input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (var i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
You use it like this:
class Program
{
static void Main(string[] args)
{
String[] pattern = new String[4];
String[] replacement = new String[4];
pattern[0] = "Quick";
pattern[1] = "Fox";
pattern[2] = "Jumped";
pattern[3] = "Lazy";
replacement[0] = "Slow";
replacement[1] = "Turtle";
replacement[2] = "Crawled";
replacement[3] = "Dead";
String DemoText = "The Quick Brown Fox Jumped Over the Lazy Dog";
Console.WriteLine(DemoText.PregReplace(pattern, replacement));
}
}
A: You can use .Select() (in .NET 3.5 and C# 3) to ease applying functions to members of a collection.
stringsList.Select( s => replacementsList.Select( r => s.Replace(s,r) ) );
You don't need regexp support, you just want an easy way to iterate over the arrays.
A: public static class StringManipulation
{
public static string PregReplace(string input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (int i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
Here is what I will use. Some code of Jonathan Holland but not in C#3.5 but in C#2.0 :)
Thx all.
A: You are looking for System.Text.RegularExpressions;
using System.Text.RegularExpressions;
Regex r = new Regex("=C0");
string output = r.Replace(text);
To get PHP's array behaviour the way you have you need multiple instances of `Regex
However, in your example, you'd be much better served by .Replace(old, new), it's much faster than compiling state machines.
A: Edit: Uhg I just realized this question was for 2.0, but I'll leave it in case you do have access to 3.5.
Just another take on the Linq thing. Now I used List<Char> instead of Char[] but that's just to make it look a little cleaner. There is no IndexOf method on arrays but there is one on List. Why did I need this? Well from what I am guessing, there is no direct correlation between the replacement list and the list of ones to be replaced. Just the index.
So with that in mind, you can do this with Char[] just fine. But when you see the IndexOf method, you have to add in a .ToList() before it.
Like this: someArray.ToList().IndexOf
String text;
List<Char> patternsToReplace;
List<Char> patternsToUse;
patternsToReplace = new List<Char>();
patternsToReplace.Add('a');
patternsToReplace.Add('c');
patternsToUse = new List<Char>();
patternsToUse.Add('X');
patternsToUse.Add('Z');
text = "This is a thing to replace stuff with";
var allAsAndCs = text.ToCharArray()
.Select
(
currentItem => patternsToReplace.Contains(currentItem)
? patternsToUse[patternsToReplace.IndexOf(currentItem)]
: currentItem
)
.ToArray();
text = new String(allAsAndCs);
This just converts the text to a character array, selects through each one. If the current character is not in the replacement list, just send back the character as is. If it is in the replacement list, return the character in the same index of the replacement characters list. Last thing is to create a string from the character array.
using System;
using System.Collections.Generic;
using System.Linq;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best place to put application data?
Possible Duplicate:
VS2008 Setup Project: Shared (By All Users) Application Data Files?
Please can someone advice what is the best place (path) to put some application data which should be accessible and editable by all users.
This is considering both Windows XP and Windows Vista and i expect that change in any file of above path does NOT trigger UAC!
A: Plain Win API: SHGetFolderPath with CSIDL_COMMON_APPDATA as folder type.
A: Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
Should resolve to C:\Documents and Settings\All Users\Application Data\
From there, make subfolders such as MyCompany\MyApp
A: VS2008 Setup Project: Shared (By All Users) Application Data Files?
A:
If you're using .NET, Application.CommonAppDataPath should work.
Also make sure that virtualization is turned off for your application
A: %ALLUSERSPROFILE%\Application Data\App
this is probably the only directory that all users can access without elevated privileges.
A: If you're using .NET, Application.CommonAppDataPath should work.
A: If the users are not going to modify the data directly, and it will only be modified by the app, how about IsolatedStorage - http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx
A: Checkers provides the vital clue to do this in C or C++. So I have voted his answer.
Here are the details he left out:
// assumes
// company is a pointer to a character sting containing company name
// appname is a pointer to a character string containing application name
// fname is a pointer to a character string cintaining name of file to be created
#include <shlobj.h> // for SHGetFolderPath
#include <direct.h> // for _mkdir
char path[MAX_PATH];
SHGetFolderPath(NULL,CSIDL_COMMON_APPDATA,NULL,NULL,path);
strcat(path,"/");
strcat(path,company);
_mkdir(path);
strcat(path,"/");
strcat(path,appname);
_mkdir(path);
strcat(path,"/");
strcat(path,fname);
// path is now a character string which can passed to fopen
A: You can also put it in a database.
A: For Vista and higher, MS seems to be pushing for using SHGetKnownFolderPath() instead of SHGetFolderPath(). Choose what folder to ask for from the list of KNOWNFOLDERIDs. Based on the answers here, the equivalent you'd want would probably be FOLDERID_ProgramData. I realize this question is quite old, but I guess for archival purposes..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Array versus linked-list Why would someone want to use a linked-list over an array?
Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort.
I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array?
This question is not a duplicate of this question because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures.
A: Fast insertion and removal are indeed the best arguments for linked lists. If your structure grows dynamically and constant-time access to any element isn't required (such as dynamic stacks and queues), linked lists are a good choice.
A: Here's a quick one: Removal of items is quicker.
A: Other than adding and remove from the middle of the list, I like linked lists more because they can grow and shrink dynamically.
A: Linked-list are especially useful when the collection is constantly growing & shrinking. For example, it's hard to imagine trying to implement a Queue (add to the end, remove from the front) using an array -- you'd be spending all your time shifting things down. On the other hand, it's trivial with a linked-list.
A: No one ever codes their own linked list anymore. That'd be silly. The premise that using a linked list takes more code is just wrong.
These days, building a linked list is just an exercise for students so they can understand the concept. Instead, everyone uses a pre-built list. In C++, based the on the description in our question, that'd probably mean an stl vector (#include <vector> ).
Therefore, choosing a linked list vs an array is entirely about weighing the different characteristics of each structure relative to the needs of your app. Overcoming the additional programming burden should have zero impact on the decision.
A: Arrays Vs Linked List:
*
*Array memory allocation will fail sometimes because of fragmented memory.
*Caching is better in Arrays as all elements are allocated contiguous memory space.
*Coding is more complex than Arrays.
*No size constraint on Linked List, unlike Arrays
*Insertion/Deletion is faster in Linked List and access is faster in Arrays.
*Linked List better from multi-threading point of view.
A: I'll add another - lists can act as purely functional data structures.
For instance, you can have completely different lists sharing the same end section
a = (1 2 3 4, ....)
b = (4 3 2 1 1 2 3 4 ...)
c = (3 4 ...)
i.e.:
b = 4 -> 3 -> 2 -> 1 -> a
c = a.next.next
without having to copy the data being pointed to by a into b and c.
This is why they are so popular in functional languages, which use immutable variables - prepend and tail operations can occur freely without having to copy the original data - very important features when you're treating data as immutable.
A: It's really a matter of efficiency, the overhead to insert, remove or move (where you are not simply swapping) elements inside a linked list is minimal, i.e. the operation itself is O(1), verses O(n) for an array. This can make a significant difference if you are operating heavily on a list of data. You chose your data-types based on how you will be operating on them and choose the most efficient for the algorithm you are using.
A: Arrays make sense where the exact number of items will be known, and where searching by index makes sense. For example, if I wanted to store the exact state of my video output at a given moment without compression I would probably use an array of size [1024][768]. This will provide me with exactly what I need, and a list would be much, much slower to get the value of a given pixel. In places where an array does not make sense there are generally better data types than a list to deal with data effectively.
A: Besides inserting into the middle of the list being easier - it's also much easier to delete from the middle of a linked list than an array.
But frankly, I've never used a linked list. Whenever I needed fast insertion and deletion, I also needed fast lookup, so I went to a HashSet or a Dictionary.
A: as arrays are static in nature, therefore all operations
like memory allocation occur at the time of compilation
only. So processor has to put less effort at its runtime .
A: Suppose you have an ordered set, which you also want to modify by adding and removing elements. Further, you need ability to retain a reference to an element in such a way that later you can get a previous or next element. For example, a to-do list or set of paragraphs in a book.
First we should note that if you want to retain references to objects outside of the set itself, you will likely end up storing pointers in the array, rather than storing objects themselves. Otherwise you will not be able to insert into array - if objects are embedded into the array they will move during insertions and any pointers to them will become invalid. Same is true for array indexes.
Your first problem, as you have noted yourself, is insertion - linked list allows inserting in O(1), but an array would generally require O(n). This problem can be partially overcome - it is possible to create a data structure that gives array-like by-ordinal access interface where both reading and writing are, at worst, logarithmic.
Your second, and more severe problem is that given an element finding next element is O(n). If the set was not modified you could retain the index of the element as the reference instead of the pointer thus making find-next an O(1) operation, but as it is all you have is a pointer to the object itself and no way to determine its current index in the array other than by scanning the entire "array". This is an insurmountable problem for arrays - even if you can optimized insertions, there is nothing you can do to optimize find-next type operation.
A: In an array you have the privilege of accessing any element in O(1) time. So its suitable for operations like Binary search Quick sort, etc. Linked list on the other hand is suitable for insertion deletion as its in O(1) time. Both has advantages as well as disadvantages and to prefer one over the other boils down to what you want to implement.
-- Bigger question is can we have a hybrid of both. Something like what python and perl implement as lists.
A: Linked List
Its more preferable when it comes about insertion! Basically what is does is that it deals with the pointer
1 -> 3 -> 4
Insert (2)
1........3......4
.....2
Finally
1 -> 2 -> 3 -> 4
One arrow from the 2 points at 3 and the arrow of 1 points at 2
Simple!
But from Array
| 1 | 3 | 4 |
Insert (2)
| 1 | 3 | | 4 |
| 1 | | 3 | 4 |
| 1 | 2 | 3 | 4 |
Well anyone can visualize the difference!
Just for 4 index we are performing 3 steps
What if the array length is one million then? Is array efficient?
The answer is NO! :)
The same thing goes for deletion!
In Linked List we can simply use the pointer and nullify the element and next in the object class!
But for array, we need to perform shiftLeft()
Hope that helps! :)
A: Linked List are more of an overhead to maintain than array, it also requires additional memory storage all these points are agreed. But there are a few things which array cant do. In many cases suppose you want an array of length 10^9 you can't get it because getting one continous memory location has to be there. Linked list could be a saviour here.
Suppose you want to store multiple things with data then they can be easily extended in the linked list.
STL containers usually have linked list implementation behind the scene.
A: 1- Linked list is a dynamic data structure so it can grow and shrink at runtime by allocating and deallocating memory. So there is no need to give an initial size of the linked list. Insertion and deletion of nodes are really easier.
2- size of the linked list can increase or decrease at run time so there is no memory wastage. In the case of the array, there is a lot of memory wastage, like if we declare an array of size 10 and store only 6 elements in it then space of 4 elements is wasted. There is no such problem in the linked list as memory is allocated only when required.
3- Data structures such as stack and queues can be easily implemented using linked list.
A: Merging two linked lists (especially two doubly linked lists) is much faster than merging two arrays (assuming the merge is destructive). The former takes O(1), the latter takes O(n).
EDIT: To clarify, I meant "merging" here in the unordered sense, not as in merge sort. Perhaps "concatenating" would have been a better word.
A: Only reason to use linked list is that insert the element is easy (removing also).
Disadvatige could be that pointers take a lot of space.
And about that coding is harder:
Usually you don't need code linked list (or only once) they are included in
STL
and it is not so complicated if you still have to do it.
A: Another good reason is that linked lists lend themselves nicely to efficient multi-threaded implementations. The reason for this is that changes tend to be local - affecting only a pointer or two for insert and remove at a localized part of the data structure. So, you can have many threads working on the same linked list. Even more, it's possible to create lock-free versions using CAS-type operations and avoid heavy-weight locks altogether.
With a linked list, iterators can also traverse the list while modifications are occurring. In the optimistic case where modifications don't collide, iterators can continue without contention.
With an array, any change that modifies the size of the array is likely to require locking a large portion of the array and in fact, it's rare that this is done without a global lock across the whole array so modifications become stop the world affairs.
A: A widely unappreciated argument for ArrayList and against LinkedList is that LinkedLists are uncomfortable while debugging. The time spent by maintenance developers to understand the program, e.g. to find bugs, increases and IMHO does sometimes not justify the nanoseconds in performance improvements or bytes in memory consumption in enterprise applicatons. Sometimes (well, of course it depends on the type of applications), it's better to waste a few bytes but have an application which is more maintainable or easier to understand.
For example, in a Java environment and using the Eclipse debugger, debugging an ArrayList will reveal a very easy to understand structure:
arrayList ArrayList<String>
elementData Object[]
[0] Object "Foo"
[1] Object "Foo"
[2] Object "Foo"
[3] Object "Foo"
[4] Object "Foo"
...
On the other hand, watching the contents of a LinkedList and finding specific objects becomes a Expand-The-Tree clicking nightmare, not to mention the cognitive overhead needed to filter out the LinkedList internals:
linkedList LinkedList<String>
header LinkedList$Entry<E>
element E
next LinkedList$Entry<E>
element E "Foo"
next LinkedList$Entry<E>
element E "Foo"
next LinkedList$Entry<E>
element E "Foo"
next LinkedList$Entry<E>
previous LinkedList$Entry<E>
...
previous LinkedList$Entry<E>
previous LinkedList$Entry<E>
previous LinkedList$Entry<E>
A: First of all, in C++ linked-lists shouldn't be much more trouble to work with than an array. You can use the std::list or the boost pointer list for linked lists. The key issues with linked lists vs arrays are extra space required for pointers and terrible random access. You should use a linked list if you
*
*you don't need random access to the data
*you will be adding/deleting elements, especially in the middle of the list
A: *
*It's easier to store data of different sizes in a linked list. An array assumes every element is exactly the same size.
*As you mentioned, it's easier for a linked list to grow organically. An array's size needs to be known ahead of time, or re-created when it needs to grow.
*Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is more complicated and/or takes more memory.
*As long as your iterations all happen in a "foreach" context, you don't lose any performance in iteration.
A: For me it is like this,
*
*Access
*
*Linked Lists allow only sequential access to elements. Thus the algorithmic complexities is order of O(n)
*Arrays allow random access to its elements and thus the complexity is order of O(1)
*Storage
*
*Linked lists require an extra storage for references. This makes them impractical for lists of small data items such as characters or boolean values.
*Arrays do not need an extra storage to point to next data item. Each element can be accessed via indexes.
*Size
*
*The size of Linked lists are dynamic by nature.
*The size of array is restricted to declaration.
*Insertion/Deletion
*
*Elements can be inserted and deleted in linked lists indefinitely.
*Insertion/Deletion of values in arrays are very expensive. It requires memory reallocation.
A: Wikipedia has very good section about the differences.
Linked lists have several advantages
over arrays. Elements can be inserted
into linked lists indefinitely, while
an array will eventually either fill
up or need to be resized, an expensive
operation that may not even be
possible if memory is fragmented.
Similarly, an array from which many
elements are removed may become
wastefully empty or need to be made
smaller.
On the other hand, arrays allow random
access, while linked lists allow only
sequential access to elements.
Singly-linked lists, in fact, can only
be traversed in one direction. This
makes linked lists unsuitable for
applications where it's useful to look
up an element by its index quickly,
such as heapsort. Sequential access on
arrays is also faster than on linked
lists on many machines due to locality
of reference and data caches. Linked
lists receive almost no benefit from
the cache.
Another disadvantage of linked lists
is the extra storage needed for
references, which often makes them
impractical for lists of small data
items such as characters or boolean
values. It can also be slow, and with
a naïve allocator, wasteful, to
allocate memory separately for each
new element, a problem generally
solved using memory pools.
http://en.wikipedia.org/wiki/Linked_list
A: Two things:
Coding a linked list is, no doubt, a bit more work than using an array and he wondered what would justify the additional effort.
Never code a linked list when using C++. Just use the STL. How hard it is to implement should never be a reason to choose one data structure over another because most are already implemented out there.
As for the actual differences between an array and a linked list, the big thing for me is how you plan on using the structure. I'll use the term vector since that's the term for a resizable array in C++.
Indexing into a linked list is slow because you have to traverse the list to get to the given index, while a vector is contiguous in memory and you can get there using pointer math.
Appending onto the end or the beginning of a linked list is easy, since you only have to update one link, where in a vector you may have to resize and copy the contents over.
Removing an item from a list is easy, since you just have to break a pair of links and then attach them back together. Removing an item from a vector can be either faster or slower, depending if you care about order. Swapping in the last item over top the item you want to remove is faster, while shifting everything after it down is slower but retains ordering.
A: Eric Lippert recently had a post on one of the reasons arrays should be used conservatively.
A: i also think that link list is more better than arrays.
because we do traversing in link list but not in arrays
A: Depending on your language, some of these disadvantages and advantages could be considered:
C Programming Language: When using a linked list (through struct pointers typically), special consideration must be made sure that you are not leaking memory. As was mentioned earlier, linked lists are easy to shuffle, because all were doing is changing pointers, but are we going to remember to free everything?
Java: Java has an automatic garbage collect, so leaking memory won't be an issue, but hidden from the high level programmer is the implementation details of what a linked list is. Methods such as removing a node from the middle of the list is more complicated of a procedure than some users of the language would expect it to be.
A: Why a linked list over an array ? Well as some have already said, greater speed of insertions and deletions.
But maybe we don't have to live with the limits of either, and get the best of both, at the same time... eh ?
For array deletions, you can use a 'Deleted' byte, to represent the fact that a row has been deleted, thus reorging the array is no longer necessary. To ease the burden of insertions, or rapidly changing data, use a linked list for that. Then when referring to them, have your logic first search one, then the other. Thus, using them in combination gives you the best of both.
If you have a really large array, you could combine it with another, much smaller array or linked list where the smaller one hold thes 20, 50, 100 most recently used items. If the one needed is not in the shorter linked list or array, you go to the large array. If found there, you can then add it to the smaller linked list/array on the presumption that 'things most recently used are most likey to be re-used' ( and yes, possibly bumping the least recently used item from the list ). Which is true in many cases and solved a problem I had to tackle in an .ASP security permissions checking module, with ease, elegance, and impressive speed.
A: While many of you have touched upon major adv./dis of linked list vs array, most of the comparisons are how one is better/ worse than the other.Eg. you can do random access in array but not possible in linked list and others. However, this is assuming link lists and array are going to be applied in a similar application. However a correct answer should be how link list would be preferred over array and vice-versa in a particular application deployment.
Suppose you want to implement a dictionary application, what would you use ?
Array : mmm it would allow easy retrieval through binary search and other search algo .. but lets think how link list can be better..Say you want to search "Blob" in dictionary. Would it make sense to have a link list of A->B->C->D---->Z and then each list element also pointing to an array or another list of all words starting with that letter ..
A -> B -> C -> ...Z
| | |
| | [Cat, Cave]
| [Banana, Blob]
[Adam, Apple]
Now is the above approach better or a flat array of [Adam,Apple,Banana,Blob,Cat,Cave] ? Would it even be possible with array ?
So a major advantage of link list is you can have an element not just pointing to the next element but also to some other link list/array/ heap/ or any other memory location.
Array is a one flat contigous memory sliced into blocks size of the element it is going to store.. Link list on the other hand is a chunks of non-contigous memory units (can be any size and can store anything) and pointing to each other the way you want.
Similarly lets say you are making a USB drive. Now would you like files to be saved as any array or as a link list ? I think you get the idea what I am pointing to :)
A:
Why would someone want to use a linked-list over an array?
This is only one reason - if you need a linked list data structure and a programming language you are using is not supports a pointers.
A: Besides convenience in insertions and deletions, the memory representation of linked list is different than the arrays. There is no restriction on the number of elements in a linked list, while in the arrays, you have to specify the total number of elements.
Check this article.
A: People using linklist must read. People will fall in love with array again.
It talks about
Out Of Order exeuction,hardware prefetch, memory latency etc.
http://www.futurechips.org/thoughts-for-researchers/quick-post-linked-lists.html
A: The difference between an array and a linked list is that an array is an index based data structure, every element is associated with an index whereas the linked list is a data structure that uses references, each node is referred to another node. In array size is fixed whereas in link list size is not fixed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "216"
} |
Q: Different dependencies for different build profiles Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?
e.g.
mvn -P debug
mvn -P release
I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.
A: Your groupId, artifactId should be tokenized in your profiles as properties and you can move your dependencies to the generic section.
A: To quote the Maven documentation on this:
A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment. Or dependencies may be pulled from different repositories based upon the JDK version used.
(Emphasis is mine)
Just put the dependency for the release profile inside the profile declaration itself and do the same for debug.
<profiles>
<profile>
<id>debug</id>
…
<dependencies>
<dependency>…</dependency>
</dependencies>
…
</profile>
<profile>
<id>release</id>
…
<dependencies>
<dependency>…</dependency>
</dependencies>
…
</profile>
</profiles>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "133"
} |
Q: Formatting a double in JSF I have a problem similar to the one found here : JSF selectItem label formatting.
What I want to do is to accept a double as a value for my and display it with two decimals. Can this be done in an easy way?
I've tried using but that seems to be applied on the value from the inputText that is sent to the server and not on the initial value in the input field.
My code so far:
<h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack">
<f:convertNumber maxFractionDigits="2" groupingUsed="false" />
</h:inputText>
EDIT: The above code actually works. I was fooled by JDeveloper that didn't update the jsp page even when I did a explicit rebuild of my project and restarted the embedded OC4J server. However, after a reboot of my computer everything was fine.
A: If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with:
<h:inputText id="text1" value="#{...}">
<f:convertNumber pattern="#,###,##0.00"/>
</h:inputText>
I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the pattern attribute is part of standard JSF.
A: If what you are trying to do is make the value of the input text field change on screen (to correct user input), you should probably look into using one of the JSF ajax frameworks like Rich Faces.
A possible example would look like this:
<h:inputText id="december" value="#{budgetMB.december}" styleClass="StandardBlack">
<f:convertNumber maxFractionDigits="2" groupingUsed="false" />
<a4j:support event="onblur" reRender="december" />
</h:inputText>
I haven't tested this, but I think it may work.
A: It seems you're actually formatting a currency. There already exists a specific formatter to handle currencies that you can assign many options to:
<f:convertNumber type="currency" />
Some interesting attributes of this tag are: locale, currencyCode, integerOnly, currencySymbol and pattern.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to get Selenium working with PHP/Firefox3 on Linux I am trying to get Selenium RC working with Firefox 3 on Linux with PHP/Apache but am experiencing problems. Here's what I've done:
*
*I have installed the Firefox Selenium-IDE extension.
*On the web server (which in my case is actually the same machine running Firefox), I've started the Selenium server with: java -jar selenium-server.jar -interactive
*I have a PHP script as follows:
PHP:
require_once 'Testing/Selenium.php';
$browser = new Testing_Selenium("*custom /usr/lib/firefox-3.0.3/firefox", "https://www.example.com");
$browser->start();
When I run the PHP script, it does launch a new Firefox tab, but I get this error message:
The requested URL /selenium-server/core/RemoteRunner.html was not found on this server.
I have had more success with Firefox 2 (by using "*firefox" instead of "*custom" but don't want to use that for my current project.
A: I'm not sure of the etiquette of answering your own question... but having experimented in a trial-and-error way, here's how I've managed to get Selenium working with PHP/Firefox3 on Ubuntu.
*
*I downloaded RC and copied the php client directory to /usr/share/php as 'Selenium'
*I navigated to the Selenium Server directory in the download, and started selenium with java -jar selenium-server.jar
*I created a new Firefox profile (by running firefox -ProfileManager). I called the new Profile 'Selenium'
*Within that profile, I editing the Firefox Network preferences to proxy all protocols via localhost port 4444.
*I created my php script and ran it with this command:
php -d include_path=".:/usr/share/php:/usr/share/php/Selenium/PEAR" test.php
I've listed my (basic, non-PHPUnit, non-OO) first test script below for reference.
require_once 'Testing/Selenium.php';
$oSelenium = new Testing_Selenium(
"*custom /usr/lib/firefox-3.0.3/firefox -P Selenium",
"https://www.example.com");
$oSelenium->start();
$oSelenium->open("/");
if (!$oSelenium->isElementPresent("id=login_button")) {
$oSelenium->click("logout");
$oSelenium->waitForPageToLoad(10000);
if (!$oSelenium->isElementPresent("id=login_button")) {
echo "Failed to log out\n\n";
exit;
}
}
$oSelenium->type("login", "my_username");
$oSelenium->type("password", "my_password");
$oSelenium->click("login_button");
$oSelenium->waitForPageToLoad(10000);
$oSelenium->click("top_nav_campaigns");
$oSelenium->stop();
A: I use phpunit, selenium RC php api to run my testcases. My testcase looks like
1235$Deepan@Newton~/selenium/ide_scripts$
cat mytest.php
'FF on linux',
'browser' => '*firefox',
'host' => '10.211.55.8',
'port' => 4444,
'timeout' => 30000,
),
array(
'name' => 'FF on windows',
'browser' => '*firefox',
'host' => '10.211.55.5',
'port' => 4444,
'timeout' => 30000,
),
*/
array(
'name' => 'Google Chrome on windows',
'browser' => '*googlechrome',
'host' => '10.211.55.5',
'port' => 4444,
'timeout' => 30000,
),
/*
array(
'name' => 'IE on windows',
'browser' => '*iexplore',
'host' => '10.211.55.5',
'port' => 4444,
'timeout' => 30000,
),
array(
'name' => 'Safari on MacOS X',
'browser' => '*safari',
'host' => 'localhost',
'port' => 4444,
'timeout' => 30000,
),
array(
'name' => 'Firefox on MacOS X',
'browser' => '*chrome',
'host' => 'localhost',
'port' => 4444,
'timeout' => 30000,
),
*/
array(
'name' => 'Google Chrome on MacOS X',
'browser' => '*googlechrome',
'host' => 'localhost',
'port' => 4444,
'timeout' => 30000,
)
);
protected function setUp()
{
//$this->setBrowser("*chrome");
$this->setBrowserUrl("http://www.facebook.com/");
}
public function testMyTestCase()
{
$this->open("/index.php?lh=94730c649368393b6954cb9fc0802e0a&eu=iKjrC7Q2aC-8tcU7PVLilg");
$this->type("email", "myemail@domain.com");
$this->type("pass", "mypassword");
$this->click("persistent");
$this->click("//input[@type='submit']");
$this->waitForPageToLoad("30000");
sleep(10);
$this->open("http://apps.facebook.com/myapp/");
sleep(4);
$this->click("link=Play");
$this->waitForPageToLoad("30000");
sleep(4);
$this->click("navAccountLink");
sleep(4);
$this->click("link=Logout");
$this->waitForPageToLoad("30000");
sleep(4);
}
}
?>
1332$Deepan@Newton~/selenium/ide_scripts$
phpunit mytest.php
This will connect to browsers running inside virtual machines
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Calling Python in PHP I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.
Any better ideas?
A: I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.
Just be extra careful if your web server is open to the internet at large. Be sure to sanitize your GET/POST input in this case so as to not allow attackers to run arbitrary commands on your machine.
A: Your call_python_file.php should look like this:
<?php
$item='Everything is awesome!!';
$tmp = exec("py.py $item");
echo $tmp;
?>
This executes the python script and outputs the result to the browser.
While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:
import sys
list1 = ' '.join(sys.argv[1:])
def main():
print list1
if __name__ == '__main__':
main()
A: The shell_exec() operator will also allow you to run python scripts using similar syntax to above
In a python file called python.py:
hello = "hello"
world = "world"
print hello + " " + world
In a php file called python.php:
$python = shell_exec(python python.py);
echo $python;
A: You can run a python script via php, and outputs on browser.
Basically you have to call the python script this way:
$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
usleep(100000);
}
pclose($pid);
Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.
For full codes working, visit How to execute python script from php and show output on browser
A: Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like
preg_replace('/[^a-zA-Z0-9]/', '', $str)
A: The above methods seems to be complex. Use my method as a reference.
I have this two files
run.php
mkdir.py
Here, I've created a html page which contains GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
A: Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: /home/user/mypython/bin/python ./cgi-bin/test.py
A: is so easy
You can use [phpy - library for php][1]
php file
<?php
require_once "vendor/autoload.php";
use app\core\App;
$app = new App();
$python = $app->python;
$output = $python->set(your python path)->send(data..)->gen();
var_dump($ouput);
python file:
import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))
you can see also example in github page
[1]: https://github.com/Raeen123/phpy
A: If you want to execute your Python script in PHP, it's necessary to do this command in your php script:
exec('your script python.py')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "87"
} |
Q: WinDbg outputs characters to console nonstop I'm developing a POS application that is used in about 200 locations as of right now using .Net 2.0, WCF and SyncFusion components for the GUI.
Two days ago we installed the application in a new location, and it has been suffering sudden termination of the application.
The application has a running log of events and exceptions, so if something happens to it, there's always something in the log. In this case, the log is simply cut off. We've had similar situations in other locations, but they were extremely rare and didn't happen more than once or twice, so we couldn't catch a debug dump.
The computer at that location has a slightly different hardware setup, including a splitter on the LPT out that is meant to be used for both printing to the POS printer, and displaying the output on a video monitor.
In this location though, it's happening about every 1.5 hours. I've tried to open WinDbg and attach to the process, but here's the weird thing, in the area where there's the debug output, I see the trace messages that my application produces, but there's also a nonstop stream of characters, specifically, "b0" that repeats itself.
My problem is that I don't understand where that "b0" is coming from, and what is it meant to be. I suspect that it might be the splitter, but I won't be able to test it until sunday.
Hope someone will have an idea how to go about solving this.
A: It sounds like you are experiencing an unmanaged exception in the application which might bypass any logging you're trying to do.
In cases like these, I set up cdb to generate a full MiniDump at the time of the crash, then I run WinDbg with the SOS extensions to analyze the dump.
From an MSDN blog (http://blogs.msdn.com/pfedev/):
Run this command from your Debugging Tools for Windows directory:
C:\debuggers> cdb -iaec "-c \".dump /u /ma c:\dumps\av.dmp;q\""
This will configure CDB debugger as the default handler for crash by AeDebug registry key. You can verify the setting by browsing to registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug
And see these two values:
Value name: Auto Value data: 1
Value name: Debugger Value data: “c:\debuggers\cdb.exe” -p %ld -e %ld -g -c “.dump /ma /u c:\av.dmp;q”
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Release COM Components Is it really necessary to release COM components from Office PIA, when you don't need them anymore by invoking Marshal.ReleaseComObject(..)?
I found various and contradictory advices on this topic on the web. In my opinion, since Outlook PIA is always returning a new references to its interfaces as returning values from its methods, it is not necessary to explicitly release it. Am I right?
A: For VS 2010, see Marshal.ReleaseComObject Is Considered Dangerous.
A: PIAs are .NET interop wrappers. This means that in the object's destructor (or Dispose - I can't remember) will automatically handle its reference count. The trick is that some references won't be released until the garbage collector is executed. It depends on what the COM object instantiates. For instance, a COM object that opens database cursors will keep those cursors alive in memory until the reference count on those cursors is released. With the .NET/COM interop, the references aren't released until the garbage collector executes or you explicitly release the reference using Marshal.ReleaseComObject (or FinalReleaseComObject).
I personally haven't worked with the Microsoft Office PIAs, but under most circumstances, you shouldn't have to explicitly release the references. It is only when your application starts to lock other resources or crash that you should start being suspicious about dangling references.
EDIT: If you run into a situation where you do need to cleanup COM/Interop objects, use Marshal.FinalReleaseComObject - which takes the reference count all the way to zero instead of just decrementing by one - and set the object reference to null. You can explicitly force garbage collection (GC.Collect) if you really want to be safe, but be careful of doing GC too often as it does invoke a noticeable performance hit.
A: With Microsoft Office, in general, you do need to explicitly release your references, which can be safely done in two stages:
(1) First release all the minor object to which you do not hold a named object variable via a call to GC.Collect() and then GC.WaitForPendingFinalizers(). (You need to call this twice, if the objects involved could have finalizers, such as when using Visual Studio Tools for Office (VSTO).)
(2) Then explicitly release the objects to which you hold a named variable via a call to Marshall.FinalReleaseComObject() on each object.
That's it. :-)
I discussed this in more detail in a previous post, along with a code example.
A: There are some good practices here using a managed wrapper..worth checking out..
A: Maybe it's just my superstition, but I decided to explicitly release the Office PIA via Marshal.ReleaseComObject() because when my application crashed, the references to Excel and Word were staying open. I didn't dig too deep into why (stupid deadlines), but releasing them as part of my class's dispose pattern fixed that problem.
A: You do need to do so if you want the instance of the Office application to exit, as described in this post.
And it's difficult to get it right in all but the most simple scenarios.
A: My experience shows that you have to, otherwise (at least Outlook) the application may not shut down at all.
But this opens another can of worms, as it looks like the RCWs are per process, thus you can break some other addin, which happens to have a reference to the same object.
I have posted a related question here, but I still have no clear answer. I'll edit this post once I know more.
A: There's one simple rule about .Net/COM interop - When in doubt, always Release(). :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/166962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.