text
stringlengths 8
267k
| meta
dict |
---|---|
Q: What's the best library for reading Outlook .msg files in Java? I would like to read the text and binary attachments in a saved Outlook message (.msg file) from a Java application, without resorting to native code (JNI, Java Native Interface).
Apache POI-HSMF seems to be in the right direction, but it's in very early stages of development...
A: msgparser is a small open source Java library that parses Outlook .msg files and provides their content using Java objects. msgparser uses the Apache POI - POIFS library to parse the message files which use the OLE 2 Compound Document format.
A: *
*You could use Apache POIFS, which
seems to be a little more mature,
but that would appear to duplicate the efforts of POI-HSMF.
*You could use POI-HSMF and contribute changes to get the
features you need working. That's
often how FOSS projects like that expand.
*You
could use com4j, j-Interop, or some
other COM-level interop feature and
interact directly with the COM
interfaces that provide access to
the structured document. That would
be much easier than trying to hit it
directly through JNI.
A: Have you tried to use Jython with the Python win32 extensions (http://www.jython.org/Project/ + http://python.net/crew/mhammond/win32/)?
If this is for a "personal" or "internal" project Jython with Python may be a very good choice. If you are building a "shrink wrapped" software package this may not be the best option.
A: Apache POI-HSMF.
You can start from the example given in below link.
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java?revision=821500&view=markup&pathrev=821500
Further read library docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Importing Access data into SQL Server using ColdFusion This should be simple. I'm trying to import data from Access into SQL Server. I don't have direct access to the SQL Server database - it's on GoDaddy and they only allow web access. So I can't use the Management Studio tools, or other third-party Access upsizing programs that require remote access to the database.
I wrote a query on the Access database and I'm trying to loop through and insert each record into the corresponding SQL Server table. But it keeps erroring out. I'm fairly certain it's because of the HTML and God knows what other weird characters are in one of the Access text fields. I tried using CFQUERYPARAM but that doesn't seem to help either.
Any ideas would be helpful. Thanks.
A: Try using the GoDaddy SQL backup/restore tool to get a local copy of the database. At that point, use the SQL Server DTS tool to import the data. It's an easy to use, drag-and-drop graphical interface.
A: What error(s) get(s) thrown? What odd characters are you using? Are you referring to HTML markup, or extended (eg UTF-8) characters?
If possible, turn on Robust Error Reporting.
If the problem is the page timing out, you can either increase the timeout using the Admin, using the cfsetting tag, or rewrite your script to run a certain number of lines, and then forward to itself at the next start point.
A: You should be able to execute saved DTS packages in MS SQL Server from the application server's command line. Since this is the case, you can use <cfexecute> to issue a request to DTSRUNNUI.EXE. (See example) This is of course assuming you are on a server where the command is available.
A: It's never advisable to loop through records when a SQL Update can be used.
It's not clear from your question what database interface layer you are using, but it is possible with the right interfaces to insert data from a source outside a database if the interface being used supports both types of databases. This can be done in the FROM clause of your SQL statement by specifying not just the table name, but the connect string for the database. Assuming that your web host has ODBC drivers for Jet data (you're not actually using Access, which is the app development part -- you're only using the Jet database engine), the connect string should be sufficient.
EDIT: If you use the Jet database engine to do this, you should be able to specify the source table something like this (where tblSQLServer is a table in your Jet MDB that is linked via ODBC to your SQL Server):
INSERT INTO tblSQLServer (ID, OtherField )
SELECT ID, OtherField
FROM [c:\MyDBs\Access.mdb].tblSQLServer
The key point is that you are leveraging the Jet db engine here to do all the heavy lifting for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When would I use Server.Transfer over PostBackURL? Or vice versa.
Update:
Hmm, let's assume I have a shopping cart app, the user clicks on the Checkout button.
The next thing I want to do is send the user to a Invoice.aspx page (or similar). When the user hits checkout, I could Button.PostBackURL = "Invoice.aspx"
or I could do
Server.Transfer("Invoice.aspx")
(I also changed the title since the method is called Transfer and not TransferURL)
A: *
*Server.TransferURL will not result
in a roundtrip of HTTP
request/response. The address bar
will not update, as far as the
browser knows it has received only
one document. Server.Transfer also retains execution context, so the script "keeps going" as opposed to "starts anew".
*PostbackURL ensures an
HTTP request, resulting in a
possibly different URL and of course
incurring network latency costs.
Usually when you are attempting to "decide between the two" it means you are better off using PostbackURL.
Feel free to expand your question with specifics and we can look at your precise needs.
A: Here is a good breakdown between the two:
Server.Transfer vs Response.Redirect
A: Server.Transfer is done entirely from the server. Postback is initiated from the client for posting form contents and postback url identifies the page to post to.
Maybe you meant to compare with Response.Redirect, which forces the client to submit a new request for a new url.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What are the C# documentation tags? In C# documentation tags allow you to produce output similar to MSDN. What are a list of allowable tags for use inside the /// (triple slash) comment area above classes, methods, and properties?
A: Check out Great documentation on the various C# XML documentation tags. (Go to the bottom to see the tags)
A: MSDN article from 2002 detailing all the tags and when to use them:
http://msdn.microsoft.com/en-us/magazine/cc302121.aspx
A: GhostDoc helps by creating a stub comment for your method/class.
A: See the excellent MSDN article here as your first stop.
A: If you type this just above a method or class, intellisense should prompt you with a list of available tags:
/// <
A: Here's a list:
*
*summary
*param
*returns
*example
*code
*see
*seealso
*list
*value
*file
*copyright
Here's an example:
<file>
<copyright>(c) Extreme Designers Inc. 2008.</copyright>
<datecreated>2008-09-15</datecreated>
<summary>
Here's my summary
</summary>
<remarks>
<para>The <see cref="TextReader"/> can be used in the following ways:</para>
<list type="number">
<item>first item</item>
<item>second item</item>
</list>
</remarks>
<example>
<code>
System.Console.WriteLine("Hello, World");
</code>
</example>
<param name="aParam">My first param</param>
<returns>an object that represents a summary</returns>
</file>
A: Look inside the docs for Sandcastle. This is the new documentation standard for .NET.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: What is the best way to randomize an array's order in PHP without using the shuffle() function? I was asked this question in a job interview. The interviewer and I disagreed on what the correct answer was. I'm wondering if anyone has any data on this.
Update: I should have mentioned that the use of shuffle() was strictly forbidden... sorry.
A: shuffle($arr);
:)
edit: I should clarify... my definition of best involves not just algorithm efficiency but code readability and maintainability as well. Using standard library functions means maintaining less code and reading much less too. Beyond that, you can get into year-long debates with PhD professors about the best "true random" function, so somebody will always disagree with you on randomization questions.
A: Well here's the solution I came up with:
function randomize_array_1($array_to_randomize) {
$new_array = array();
while (count($array_to_randomize) > 0) {
$rand_num = rand(0, count($array_to_randomize)-1);
$extracted = array_splice($array_to_randomize, $rand_num, 1);
$new_array[] = $extracted[0];
}
return $new_array;
}
And here's his solution:
function randomize_array_2($array_to_randomize) {
usort($array_to_randomize, "rand_sort");
return $array_to_randomize;
}
function rand_sort($a, $b) {
return rand(-1, 1);
}
I ran a bunch of trials on both methods (trying each 1,000,000 times) and the speed difference was negligible. However, upon checking the actual randomness of the results I was surprised at how different the distributions were. Here's my results:
randomize_array_1:
[2, 3, 1] => 166855
[2, 1, 3] => 166692
[1, 2, 3] => 166690
[3, 1, 2] => 166396
[3, 2, 1] => 166629
[1, 3, 2] => 166738
randomize_array_2:
[1, 3, 2] => 147781
[3, 1, 2] => 73972
[3, 2, 1] => 445004
[1, 2, 3] => 259406
[2, 3, 1] => 49222
[2, 1, 3] => 24615
As you can see, the first method provides an almost perfect distribution indicating that it's being more-or-less truly random, whereas the second method is all over the place.
A: You could use the Fisher-Yates shuffle.
A: He's probably testing you on a relatively common mistake most people make when implementing a shuffling algorithm (this was also actually at the center of a controversy involving an online poker site a few years back)
Incorrect way to shuffle:
for (i is 1 to n)
Swap i with random position between 1 and n
Correct way to shuffle:
for (i is 1 to n)
Swap i with random position between i and n
Graph out the probability distribution for these cases and it's easy to see why the first solution is incorrect.
A: The "correct" way is pretty vague. The best (fastest / easiest / most elegant) to sort an array would be to just use the built-in shuffle() function.
A: PHP has a built in function --> shuffle() . I would say that should do what you like, but it mostly likely will be anything but totally 'random'.
Check http://computer.howstuffworks.com/question697.htm for a little description of why its very, very difficult to get complete randomness form a computer.
A: Short Answer: PHP's array_rand() function
Given that the use of the shuffle function is forbidden, I would use $keys = array_rand($myArray, count($myArray)) to return an array of the keys from $myArray in random order. From there it should be simple to reassemble them into a new array that has been randomized. Something like:
$keys = array_rand($myArray, count($myArray));
$newArray = array();
foreach ($keys as $key) {
$newArray[$key] = $myArray[$key];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: report generation on php? one of the most frequent requests I get is to create XY report for YZ App. These apps are normally built on PHP, so far I have manually created most of this reports, and while I enjoy the freedom of building it as I want, it usually becomes pretty tedious to calculate subtotals, averages, exporting to different formats etc.
What solutions are out there (free/OSS preferred) that help me get this repetitive tasks cranking?
edits:
*
*I'm talking about reports/summaries from SQL data. Many times from DBs not designed for reporting use.
*while I'm aware of "business-intelligence" we're not ready to implement a full scaled "intelligence" structure, looking more for a helper of sorts...
A: The problem you're facing is solved by so-called Business Intelligence software. This software tends to be bloated and expensive, but if you know your way around them you will be able to crank out such reports in no time at all.
I'm only familiar with one particular proprietary solution, which isn't too great either. But a quick search turns up the following page, which lists a number of free/open source alternatives:
http://en.wikipedia.org/wiki/Business_intelligence_tools
A: It depends on what kind of reports you're talking about. For example... site stats... you could install google analytics and the client could export whatever format they wanted.
A: A little Google search gave me the following OSS:
RLib
http://rlib.sicompos.com/
PM Report
http://www.hotscripts.com/Detailed/48187.html
I don't have any information on them, sorry.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Anyone know of a list of delegates already built into the framework? I find myself writing delegates occasionally for really simple functions (take no arguments and return void for example) and am wondering if anyone knows someplace that has compiled a list of all the predefined delegates already available in the .NET framework so I can reuse them?
To be clear I am looking for something like this:
*
*void System.AsyncCallback(System.IAsyncResult)
*int System.Comparison(T x, T y)
*void System.IO.ErrorEventHandler(object, System.Io.ErrorEventArgs)
and so on
If not, sounds like a good idea for a blog article.
A: Just look in the msdn database for (T) delegate.
Here you got a direct link: List of delegates
That should get you started.
A: I have previously blogged along these lines here. Basically, I describe how you can find an existing delegate to meet your needs using Reflector.
A: One thing to keep in mind is that you write code to be readable to future coders, including your future self. Even if you can find a built-in delegate with the correct signature in the framework, it's not always correct to use that delegate if it obscures the purpose of the code.
Six months down the road, the use of a delegate of type BondMaturationAction is going to be much clearer than that of one with a type Action, even if the signatures are the same.
A: Just use the Action, Action<T>, Action<T1,T2,..> delegates for methods not returning anything (void), or the Func<TResult>, Func<T, TResult>, Func<T1, ..., TResult> delegates for methods returning TResult.
Those delegates are new in .net 3.5.
A: In .NET 2.0 and later, use EventHandler if you have no arguments at all, and EventHandler<T> if you want to provide some custom data (you will need to derive a class from EventArgs with your additional data in it). If you have no EventArgs to use, pass EventArgs.Empty.
Because EventArgs is a reference type, all instances of EventHandler<T> use the same JITted code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What is the best way to extract a version string from a file? I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory.
For Example, if the run directory looks like this:
.
..
1.2.1
1.2.2
1.3.0
run.sh
current_version
And current_version contains:
1.2.2
I want run.sh to descend into 1.2.2 and run the program foo.
The current solution is this:
#!/bin/sh
version = `cat current_version`
cd $version
./foo
It works but is not very robust. It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc.
What is the most survivable way to do this with either a shell or perl script?
A: That's a common approach. You can check for dir/file existence using test operators such as "if [ -d "somedirectory" ]; then" or [ -t "somefile" ]
I use symbolic links more often, though. Then, you can just change your symbolic link to use the version you want.
For example,
$ ln -s 1.2.2 current_version
$ ls -al
total 20
drwxr-xr-x 5 dbreese dbreese 4096 2008-09-15 13:34 .
drwxr-xr-x 3 dbreese dbreese 4096 2008-09-15 13:34 ..
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.1
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.2
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.3.0
lrwxrwxrwx 1 dbreese dbreese 6 2008-09-15 13:34 current_version -> 1.2.2/
Then your script can just use "cd current_version".
A: I would change the script to accept an argument. The argument should be a filename. Open the file using whatever scripting language you prefer [perl, python] and traverse the file until you find a match for your version.
I would use a regex... something along the lines of /\d\.\d\.\d/ . then have it execute the application through your script.
A: You can check for existence using the && and || operators:
!$/bin/sh
version = `cat current_version`
cd $version && ./foo || echo "Bad version"
The && operator causes the second statement to only execute if the first one succeeds (exit status 0), and the || operator causes the second statement to execute only if the first one fails (exit status non-zero).
I'm not sure what you mean by coping with multiple lines, leading spaces, or commented lines.
A: If the versioning will always be in #.#.# format, you could do this:
ls | grep ^[0-9]\.[0-9]\.[0-9]$ | sort -nr | head -n 1
That will list the versions in descending numerical order, then selects the first of those
A: What about:
#!/usr/bin/perl -w
use strict;
use warnings;
my $version_file = 'current_version';
open my $fh, '<', $version_file or die "Can't open $version_file: $!";
# Read version from file
my $version = <$fh>;
chomp $version;
# Remove whitespace (and match version)
die "Version format not recognized" if $version !~ m/(\d+\.\d+\.\d+)/;
my $dir = $1;
die "Directory not found: $dir" unless -d $dir;
# Execute program in versioned directory.
chdir $dir;
system("./foo");
A: !#/bin/sh
if [ -e 'current_version' ]; then
version=`cat current_version`;
version=`echo $version | tr -ds [[:blank:]]`
if [ -n "$version" ]; then
if [ -d "$version" ]; then
cd "$version"
else
echo $version is not a directory
fi
else
echo version_file contained only blanks
fi
else
No file named current_version exists
fi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Apps that support both DirectX 9 and 10 I have a noobish question for any graphics programmer.
I am confused how some games (like Crysis) can support both DirectX 9 (in XP) and 10 (in Vista)?
What I understand so far is that if you write a DX10 app, then it can only runs in Vista.
Maybe they have 2 code bases -- one written in DX9 and another in DX10? But isn't that an overkill?
A: They have two rendering pipelines, one using DX9 calls and one using DX10 calls. The APIs are not compatible, though a majority of any game engine can be reused for either. If you want some Open Source examples of how different rendering pipelines are done, look at something like Ogre3d, which supports OpenGL, DX9, and (soon)DX10 rendering.
A: The rendering layer of games is usually a fairly well isolated/abstracted part of the whole application. As far as the game engine is concerned, each frame you are simply building up a list of conceptual objects (trees, characters, etc.). If the game engine chooses to render a particular object, then it's up to the rendering layer how to actually translate that intent into DX draw calls. A DX10 rendering will generate a different set of draw calls to a DX9 layer, but conceptually they are still performing the same action - 'render this tree'.
Rendering is nicely abstracted because it's rare that you want to get any information back from the rendering layer, once the 'render this tree' action is performed, the game engine will just assume that the rendering looks correct. There is little need to handle different potential results from DX9/DX10 rendering calls because 99.9% of the information is going from the engine to the graphics system, and the 0.1% that comes back likely takes the same form between the two APIs.
The application setup is a little more icky, because you've got to ask the system whether or not DX10 is supported and gracefully fall back on DX9 otherwise, but this is standard fare for application setup (in the same way that the game has to pick a resolution, refresh rate, input device, etc.).
A: It is likely that they have an abstraction layer and they develop against that. At run-time they instantiate the DX9 or DX10 wrapping concrete engines.
I imagine their abstraction is positioned very close to the DirectX layer and simply provides DX9 with sensible manual implementations of DX10 functions or enhances DX9 logic when running on DX10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: JavaScript in client-side XSL processing? Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations? How is it done and how official is it?
Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET).
Clarification: I do not mean HTML DOM scripting performed after the document is transformed, nor do I mean XSL transformations initiated by JavaScript in the browser (e.g. what the W3Schools page shows). I am referring to actual script blocks located within the XSL during the transformation.
A: To embed JavaScript for the aid of transformation you can use <xsl:script>, but it is limited to Microsoft's XML objects implementation. Here's an example:
scripted.xml:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="scripted.xsl"?>
<data a="v">
ding dong
</data>
scripted.xsl:
<?xml version="1.0" encoding="ISO-8859-1"?>
<html xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:script implements-prefix="local" language="JScript"><![CDATA[
function Title()
{
return "Scripted";
}
function Body(text)
{
return "/" + text + "/";
}
]]></xsl:script>
<head>
<title><xsl:eval>Title()</xsl:eval></title>
</head>
<body>
<xsl:for-each select="/data"><xsl:eval>Body(nodeTypedValue)</xsl:eval></xsl:for-each>
</body>
</html>
The result in Internet Explorer (or if you just use MSXML from COM/.NET) is:
<html>
<head>
<title>Scripted</titlte>
</head>
<body>
/ding dong/
</body>
</html>
It doesn't appear to support the usual XSL template constructs and adding the root node causes MSXML to go into some sort of standards mode where it won't work.
I'm not sure if there's any equivalent functionality in standard XSL, but I can dream.
A: I don't think you can execute JavaScript code embedded inside XML documents. Like, helios mentioned, you can preform the transformation using JavaScript.
JavaScript is embedded as CDATA in most cases, which is usually used after the XSL transformation has taken place. If I understand correctly, you want to have an executable <script> tag in your XML.
You could use XSL parameters and templates if you need a more control on your transformations. You can set these values in your XSLT and then pass them to exec(). Mozilla supports setting parameters in XSL, but I'm not sure about other browsers.
Also, cross-browser JavaScript/XSLT is a pain in the neck. Mozilla's JavaScript/XSLT interface is very different than IE's, so you might want to rely on a browser-independent library like jQuery's XSLT.
A: Yes. It's browser dependant but you can use Javascript. There is a small but practical tutorial on w3schools.com. It's part of the XSLT tutorial.
The page:
http://www.w3schools.com/xsl/xsl_client.asp
The XSLT tutorial:
http://www.w3schools.com/xsl/default.asp
That site will be more helpful than myself. Good luck!
A: I doubt you'll find what you're looking for if "official" means "standards-based." What you describe is a user-agent scripting language to be parsed and executed during a style-sheet parsing. If your aim is to simplify XSLT by doing the dirty work in Javascript, you may be better off trying to generate the XSLT in javascript and then using a class wrapper to parse the result in via the browser's own XSLT parser.
This is of course a lot more work than you probably signed on for, but if you're convinced you want to do so, I'd take look at John Resig's Javascript Micro-Templates to dynamically store template-friendly XSLT in your javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Auto-updating in Corporate Environments (C#) I have a three-tier application which is installed in corporate environments. With every server version update, all clients have to be updated, too. Currently, I provide an MSI package which is automatically deployed via Active Directory, however my customers (mostly with 20-300 users each) seem to hate the MSI solution because it is
*
*Complicated to get it running (little Active Directory knowledge);
*The update process can't be triggered by the server, when a new version is detected;
*Customers can't install multiple versions of the client (e.g. 2.3 and 2.4) at the same time to speak to different servers;
*The update process itself doesn't always work as expected (sometimes very strange behaviour healing itself after a few hours)
I've now made a few experiments with ClickOnce, but that way to unflexible for me and too hard to integrate in my automated build process. Also, it produces cryptic error messages which would surely confuse my customers.
I would have no problems to write the update logic myself, but there the problem is that the users running to self-updating applications have too restricted rights to perform an update. I've found that they are able to write to their Local Application Data directory, but I don't think this would be the typical place to install application files into.
Do you know a way to an update that "just works"?
A: You can somewhat replicate what ClickOnce does, just adjust it for your needs.
*
*Create a lightweight executable that checks a network/web location for updates.
*If there are updates, it copies them locally and replaces the "real" application files.
*It runs the "real" application.
The location for the application files should be determined by permissions and operating system. If users only have write permission to a limited set of folders, then you don't have a choice but use one of these folders. Another option is provide an initial installation package that installs the lightweight executable and grants r/w permission on a specific folder such as "C:\Program Files\MyApp". This approach usually requires a buy-in from IT.
I hope this helps.
A: It is really hard to provide you exact answers because critical information about the client side installer is not explicit. Do you install client side files into Program Files? Then you may meet problems when users are restricted.
You don't think Local Application Data is a folder to deploy application, but Google does. Its Chrome browser installs that way on Windows, and its automatic update process is even unnoticable (which may sound horrible). So why not deploy your application into this folder for restricted users? You may find more about Chrome installer here,
http://robmensching.com/blog/archive/2008/09/04/Dissecting-the-Google-Chrome-setup.aspx
A: Here's an open-source solution I wrote to address specific needs we had for WinForms and WPF apps. The general idea is to have the greatest flexibility, at the lowest overhead possible. It should give you all the flexibility you need for all that you have described.
So, integration is super-easy, and the library does pretty much everything for you, including synchronizing operations. It is also highly flexible, and lets you determine what tasks to execute and on what conditions - you make the rules (or use some that are there already). Last by not least is the support for any updates source (web, BitTorrent, etc) and any feed format - whatever is not implemented you can just write for yourself.
Cold updates (requiring an application restart) is also supported, and done automatically unless "hot-swap" is specified for the task.
This boild down to one DLL, less than 70kb in size.
More details at http://www.code972.com/blog/2010/08/nappupdate-application-auto-update-framework-for-dotnet/
Code is at http://github.com/synhershko/NAppUpdate (Licensed under the Apache 2.0 license)
I plan on extending it more when I'll get some more time, but honestly you should be able to quickly enhance it yourself for whatever it currently doesn't support.
A: If you don't want to give your users too many rights, it is possible to write a Windows Service, which will run on each computer under an account with the appropriate privileges, and which can update your application, when a new version gets available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How would you implement a breadcrumb helper in asp.net mvc? I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.
A: @Chris: something like this:
<%
foreach (var item in ViewData.Get<Breadcrumb[]>())
{
%>
<a href="<%= Server.HtmlEncode(item.Url) %>"><%= item.LinkText %></a> »
<%
}
%>
A: We are using an action filter for this.
...
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (Controller) filterContext.Controller;
Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText);
controller.ViewData.Add(breadcrumbs);
}
before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options. IBreadcrumbManager looks like this:
public interface IBreadcrumbManager
{
Breadcrumb[] PushBreadcrumb(string linkText);
}
The implementation puts Breadcrumb objects into the Session. The Url is HttpContext.Current.Request.RawUrl
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: How do I best localize an entire app to many different languages? I'm using Visual Studio (2005 and up). I am looking into trying out making an application where the user can change language for all menues, input formats and such. How would I go on doing this, as I suppose that there is some complete feature within .Net that can help me with this?
I need to take the following into account (and fill me in if I miss some obvious stuff)
*
*Strings (menues, texts)
*Input data (parsing floats, dates, etc..)
*Should be easy to add support for another language
A: I'm not an expert with .NET by any means but Localization is never just as simple as "swapping out String values" or "changing date formats". There is much more to be taken into consideration such as layout, proper text placement.
Take Chinese for example. The way you read is top to bottom not left to right. If properly localized the app should take that into account.
http://msdn.microsoft.com/en-us/library/y99d1cd3(VS.80).aspx seems to be a good start though if you're dealing with Windows Forms.
A: The classic recipe is: design the app with no native language but a localization facility, and develop an initialization into one language (e.g., English). So you build the app and localize it into English every night; without the localization step it would not be usable. Do that well, and the resources for the initial sample localization can be replaced with those for any other language. Take into account non-roman scripts from the beginning. It's much cleaner to have a no-language app that always requires localization rather than a language-specific app that needs to have its native language subtracted and a replacement added.
A: For strings you should just separate your strings from your code (having an XML/DLL that will transform string IDs to real strings is one way to go). However you do need to make sure that you are supporting double byte characters for some languages (this is relevant if you use C/C++).
For input data what you want is to have different locale's. In Java this is relatively easy, and if you use C# it probably is quite easy also. In C/C++ I don't really know. The basic idea is that the input parsers should be different based on the locale selected at that time. So each field (textfield, textbox, etc.) must have an abstract parser that is then implemented by a different class depending on the locale (right to left, double byte, etc.).
Check the Java implementation for details on how they did it. It is quite functional.
A: You definitely need to be using the .NET ResourceManager and the resx file xml format, however there are a number of approaches to using this.
It really depends on what you are wanting to achieve. For me I wanted a single xml resource file (for each supported language) that could be modified by anyone. I created a helper class that loaded the global resource file into ResourceManager (once only) and I had a helper function that gives me the required resource for a given name. The only disadvantage in this approach was that I could not leverage dynamic binding of resources to properties.
I found this better and easier to manage than multiple or embedded resource files for every form. Additionally exactly the same approach can used in an ASP.NET application. I also found this approach means that outsourcing translation of resources and shipping language packs to customers much more manageable.
A: Microsoft's recommended approach is to use satellite assemblies, as described in Packaging and Deploying Resources. If you're using a ResourceManager to load resources, .NET will load the correct resources for the CurrentUICulture. This defaults to the user's current UI language setting in Windows.
It is possible to localize Windows Forms either through Visual Studio or an external tool, WinRes.exe. This article describes WinRes and how to use Visual Studio to localize the form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What is the best implementation of an exception mechanism? Most program languages have some kind of exception handling; some languages have return codes, others have try/catch, or rescue/retry, etc., each with its own pecularities in readability, robustness, and practical effectiveness in a large group development effort. Which one is the best and why ?
A: I would say that depends on the nature of your problem. Different problem domains could require almost arbitrary error messages, while other trivial tasks just can return NULL or -1 on error.
The problem with error return codes is that you're polluting/masking the error since it can be ignored (sometimes without the API client not knowing they should check for the error code). It gives a (reasonably) valid output from the method at hand.
Imagine you have an API where you ask for a index key for some map, store it in a list, and then continue running. The API then at a later moment sends a callback, and that method might then traverse the table, using the key which might be -1 in this example (the error code). BOOM, the application crashes as you index to -1 in some array, and those kinds of problems can be very hard to nail down. This is still a trivial example, but it illustrates a problem with error codes.
On the other hand, error codes are faster than throwing exceptions, and you might want to use them for frequently accessed method calls - if it is appropriate to return such an error code. I would say that trying to encapsulate these kinds of error codes within a private assembly would be quite OK since you're not exposing those error codes to the client of the API. Always remember to document these methods rigorously since these kinds of application nukes can linger around in an application for a long time since they were triggered before it goes off.
Personally, I prefer a mix of them both to some extent. I use exceptions just for that - exceptions - when the program runs into a state which was not expected and needs to inform something has gone way out of plan. I am not a sucker of writing try/catch blocks all over my code, but it's all down to personal preference.
A: Best for what? Language design is always about tradeoffs. The advantage of return codes is that they don't require any runtime support beyond regular function calls; the disadvantages are 1) you always have to check them 2) the return type has to have a failure value that isn't a valid result of the function call.
The advantage of automatic exception handling is that error conditions in your code don't disappear.
The differences between exception handling semantics in various languages (and Lisp's condition system, E's ejectors, etc) mainly show up in how stack unwinding is dealt with when program execution should continue.
To summarize, though: automatic exception handling is extremely valuable when you need to write readable, robust software, especially in a large team. Letting the computer track error conditions for you gives you one less thing to think about when reading code, and it removes an opportunity for error. The only time I'd use return codes to indicate errors is if I was implementing a language with exception handling in one that didn't have it.
A: try/catch/finally does the job admirably.
It allows the programmer to handle specific conditions as well as general failures gracefully.
All said and done I'm sure that each is as good as any other.
A: I'd have to go with the try / catch concept. I feel like in terms of readability this provides the most to a code maintainer. It should be fairly straight forward to find the chain of function calls as long as the exception is properly typed and the associated message contains detailed enough data (I personally do not like including stack traces but I know plenty who do and this would make this even more traceable.) The return code implementation requires an external table of code definitions on a program by program basis. Which from personal experience is both unwieldy to maintain and reference.
A: For unusual perspective on exception handling, see Haskell's Control.Exception monad
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Order of DOM NodeList returned by getChildNodes() The DOM method getChildNodes() returns a NodeList of the children of the current Node. Whilst a NodeList is ordered, is the list guaranteed to be in document order?
For example, given <a><b/><c/><d/></a> is a.getChildNodes() guaranteed to return a NodeList with b, c and d in that order?
The javadoc isn't clear on this.
A: In my experience, yes. The DOM spec isn't any clearer. If you're paranoid, try something like
current = node.firstChild;
while(null != current) {
...
current = current.nextSibling;
}
A: A document-ordered node list is the behavior in other implementations of the DOM, such as Javascript's or Python's. And a randomly-ordered node list would be utterly useless. I think it's safe to depend on nodes being returned in document order.
A: My experience is that every time that I have bothered to look it has been in document order. However, I believe that I read somewhere it is not guaranteed to be in document order. I can't find where I read that right now, so take it as hearsay. I think your best bet if you must have them in document order would be to use FirstChild then NextSibling until there are no more sibs.
A: I'd love to tell you that this is guaranteed (as I believe it is) but the Document Object Model specification itself seems ambiguous in this case. I'm pretty sure that it's always document-order, though.
A: In your example, as presented. I believe so. However, I've experienced real-world experiences where spaces have been interpreted as nodes so:
<a><b/><c/><d/></a>
is different than
<a><b/> <c/><d/></a>
if you're looking at index [1], firefox and IE may present different results. I would advise against relying on the order depending on your need.
A: Yes they are ordered as it returns a nodeList, you would have to say getNamedChildNodes to get a list that is not ordered as in namedNodeList.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Application Level Replication Technologies I am building out a solution that will be deployed in multiple data centers in multiple regions around the world, with each data center having a replicated copy of data actively updated in each region. I will have a combination of multiple databases and file systems in each data center, the state of which must be kept consistent (within a data center). These multiple repositories will be fronted by a SOA service tier.
I can tolerate some latency in the replication, and need to allow for regions to be off-line, and then catch up later.
Given the multiple back end repositories of data, I can't easily rely on independent replication solutions for each one to maintain a consistent state. I am thus lead to implementing replication at the application layer -- by replicating the SOA requests in some manner. I'll need to make sure that replication loops don't occur, and that last writer conditions are sorted out correctly.
In your experience, what is the best pattern for solving this problem, and are there good products (free or otherwise) that should be investigated?
A: Lotus/ Domino is your answer. I've been working with it for ten years and its exactly what you need. It may not be trendy (a perception that I would challenge) but its powerful, adaptable and very secure, The latest version R8 is the best yet.
A: You should definitely consider IBM Lotus Domino. A Lotus Notes database can replicate between sites on a predefined schedule. The replicate in Notes/Domino is definitely a very powerful feature and enables for full replication of data between sites. Even if a server is unavailable the next time it connects it will simply replicate and get back in sync.
As far as SOA Service tier you could then use Domino Designer to write a webservice. Since Notes/Domino 7.5.x (I believe) Domino has been able to provision and consume webservices.
A: AS what other advised, I will recommend also Lotus Notes/Domino. 8.5 is really very powerful application development platfrom
A: You dont give enough specifics to be certain of your needs but I think you should check out SQL Server Merge replication. It allows for asynchronous replication of multiple databases with full conflict resolution. You will need to designate a Global master and all the other databases will replicate to that one, but all the database instances are fully functional (read/write) and so you can schedule replication at whatever intervals suit you. If any region goes offline they can catch up later with no issues - if the master goes offline everyone will work independantly until replication can resume.
I would be interested to know of other solutions this flexible (apart from Lotus Notes/Domino of course which is not very trendy these days).
A: I think that your answer is going to have to be based on a pub/sub architecture. I am assuming that you have reliable messaging between your data centers so that you can rely on published updates being received eventually. If all of your access to the data repositories is via service you can add an event notification to the orchestration of each of your update services that notifies all interested data centers of the event. Ideally the master database is the only one that sends out these updates. If the master database is the only one sending the updates you can exclude routing the notifications to the node that generated them in the first place thus avoiding update loops.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to sort by Lucene.Net field and ignore common stop words such as 'a' and 'the'? I've found how to sort query results by a given field in a Lucene.Net index instead of by score; all it takes is a field that is indexed but not tokenized. However, what I haven't been able to figure out is how to sort that field while ignoring stop words such as "a" and "the", so that the following book titles, for example, would sort in ascending order like so:
*
*The Cat in the Hat
*Horton Hears a Who
Is such a thing possible, and if yes, how?
I'm using Lucene.Net 2.3.1.2.
A: I wrap the results returned by Lucene into my own collection of custom objects. Then I can populate it with extra info/context information (and use things like the highlighter class to pull out a snippet of the matches), plus add paging. If you took a similar route you could create a "result" class/object, add something like a SortBy property and grab whatever field you wanted to sort by, strip out any stop words, then save it in this property. Now just sort the collection based on that property instead.
A: When you create your index, create a field that only contains the words you wish to sort on, then when retrieving, sort on that field but display the full title.
A: It's been a while since I used Lucene but my guess would be to add an extra field for sorting and storing the value in there with the stop words already stripped. You can probably use the same analyzers to generate this value.
A: There seems to be a catch-22 in that you must tokenize a field with an analyzer in order to strip punctuation and stop words, but you can't sort on tokenized fields. How then to strip the stop words without tokenizing?
A: For search, I found search lucene .net index with sort option link interesting to solve ur problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to implement constants in Java? I've seen examples like this:
public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.
A: That's the right way to go.
Generally constants are not kept in separate "Constants" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.
A: What about an enumeration?
A: I agree that using an interface is not the way to go. Avoiding this pattern even has its own item (#18) in Bloch's Effective Java.
An argument Bloch makes against the constant interface pattern is that use of constants is an implementation detail, but implementing an interface to use them exposes that implementation detail in your exported API.
The public|private static final TYPE NAME = VALUE; pattern is a good way of declaring a constant. Personally, I think it's better to avoid making a separate class to house all of your constants, but I've never seen a reason not to do this, other than personal preference and style.
If your constants can be well-modeled as an enumeration, consider the enum structure available in 1.5 or later.
If you're using a version earlier than 1.5, you can still pull off typesafe enumerations by using normal Java classes. (See this site for more on that).
A: I prefer to use getters rather than constants. Those getters might return constant values, e.g. public int getMaxConnections() {return 10;}, but anything that needs the constant will go through a getter.
One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.
The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.
A: That is perfectly acceptable, probably even the standard.
(public/private) static final TYPE NAME = VALUE;
where TYPE is the type, NAME is the name in all caps with underscores for spaces, and VALUE is the constant value;
I highly recommend NOT putting your constants in their own classes or interfaces.
As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
For example:
public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
That is legal and ORIGIN would then be a point at (3, 0).
A: Based on the comments above I think this is a good approach to change the old-fashioned global constant class (having public static final variables) to its enum-like equivalent in a way like this:
public class Constants {
private Constants() {
throw new AssertionError();
}
public interface ConstantType {}
public enum StringConstant implements ConstantType {
DB_HOST("localhost");
// other String constants come here
private String value;
private StringConstant(String value) {
this.value = value;
}
public String value() {
return value;
}
}
public enum IntConstant implements ConstantType {
DB_PORT(3128),
MAX_PAGE_SIZE(100);
// other int constants come here
private int value;
private IntConstant(int value) {
this.value = value;
}
public int value() {
return value;
}
}
public enum SimpleConstant implements ConstantType {
STATE_INIT,
STATE_START,
STATE_END;
}
}
So then I can refer them to like:
Constants.StringConstant.DB_HOST
A: In Effective Java (2nd edition), it's recommended that you use enums instead of static ints for constants.
There's a good writeup on enums in Java here:
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
Note that at the end of that article the question posed is:
So when should you use enums?
With an answer of:
Any time you need a fixed set of constants
A: A good object oriented design should not need many publicly available constants. Most constants should be encapsulated in the class that needs them to do its job.
A: I would highly advise against having a single constants class. It may seem a good idea at the time, but when developers refuse to document constants and the class grows to encompass upwards of 500 constants which are all not related to each other at all (being related to entirely different aspects of the application), this generally turns into the constants file being completely unreadable. Instead:
*
*If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+.
*If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant)
*If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.
A: Just avoid using an interface:
public interface MyConstants {
String CONSTANT_ONE = "foo";
}
public class NeddsConstant implements MyConstants {
}
It is tempting, but violates encapsulation and blurs the distinction of class definitions.
A: There is a certain amount of opinion to answer this. To start with, constants in java are generally declared to be public, static and final. Below are the reasons:
public, so that they are accessible from everywhere
static, so that they can be accessed without any instance. Since they are constants it
makes little sense to duplicate them for every object.
final, since they should not be allowed to change
I would never use an interface for a CONSTANTS accessor/object simply because interfaces are generally expected to be implemented. Wouldn't this look funny:
String myConstant = IMyInterface.CONSTANTX;
Instead I would choose between a few different ways, based on some small trade-offs, and so it depends on what you need:
1. Use a regular enum with a default/private constructor. Most people would define
constants this way, IMHO.
- drawback: cannot effectively Javadoc each constant member
- advantage: var members are implicitly public, static, and final
- advantage: type-safe
- provides "a limited constructor" in a special way that only takes args which match
predefined 'public static final' keys, thus limiting what you can pass to the
constructor
2. Use a altered enum WITHOUT a constructor, having all variables defined with
prefixed 'public static final' .
- looks funny just having a floating semi-colon in the code
- advantage: you can JavaDoc each variable with an explanation
- drawback: you still have to put explicit 'public static final' before each variable
- drawback: not type-safe
- no 'limited constructor'
3. Use a Class with a private constructor:
- advantage: you can JavaDoc each variable with an explanation
- drawback: you have to put explicit 'public static final' before each variable
- you have the option of having a constructor to create an instance
of the class if you want to provide additional functions related
to your constants
(or just keep the constructor private)
- drawback: not type-safe
4. Using interface:
- advantage: you can JavaDoc each variable with an explanation
- advantage: var members are implicitly 'public static final'
- you are able to define default interface methods if you want to provide additional
functions related to your constants (only if you implement the interface)
- drawback: not type-safe
A:
What is the best way to implement constants in Java?
One approach that we should really avoid : using interfaces to define constants.
Creating a interface specifically to declare constants is really the worst thing : it defeats the reason why interfaces were designed : defining method(s) contract.
Even if an interface already exists to address a specific need, declaring the constants in them make really not sense as constants should not make part of the API and the contract provided to client classes.
To simplify, we have broadly 4 valid approaches.
With static final String/Integer field :
*
*1) using a class that declares constants inside but not only.
*1 variant) creating a class dedicated to only declare constants.
With Java 5 enum :
*
*2) declaring the enum in a related purpose class (so as a nested class).
*2 variant) creating the enum as a standalone class (so defined in its own class file).
TLDR : Which is the best way and where locate the constants ?
In most of cases, the enum way is probably finer than the static final String/Integer way and personally I think that the static final String/Integer way should be used only if we have good reasons to not use enums.
And about where we should declare the constant values, the idea is to search whether there is a single existing class that owns a specific and strong functional cohesion with constant values. If we find such a class, we should use it as the constants holder. Otherwise, the constant should be associated to no one particular class.
static final String/ static final Integer versus enum
Enums usage is really a way to strongly considered.
Enums have a great advantage over String or Integer constant field.
They set a stronger compilation constraint.
If you define a method that takes the enum as parameter, you can only pass a enum value defined in the enum class(or null).
With String and Integer you can substitute them with any values of compatible type and the compilation will be fine even if the value is not a defined constant in the static final String/ static final Integer fields.
For example, below two constants defined in a class as static final String fields :
public class MyClass{
public static final String ONE_CONSTANT = "value";
public static final String ANOTHER_CONSTANT = "other value";
. . .
}
Here a method that expects to have one of these constants as parameter :
public void process(String constantExpected){
...
}
You can invoke it in this way :
process(MyClass.ONE_CONSTANT);
or
process(MyClass.ANOTHER_CONSTANT);
But no compilation constraint prevents you from invoking it in this way :
process("a not defined constant value");
You would have the error only at runtime and only if you do at a time a check on the transmitted value.
With enum, checks are not required as the client could only pass a enum value in a enum parameter.
For example, here two values defined in a enum class (so constant out of the box):
public enum MyEnum {
ONE_CONSTANT("value"), ANOTHER_CONSTANT(" another value");
private String value;
MyEnum(String value) {
this.value = value;
}
...
}
Here a method that expects to have one of these enum values as parameter :
public void process(MyEnum myEnum){
...
}
You can invoke it in this way :
process(MyEnum.ONE_CONSTANT);
or
process(MyEnum.ANOTHER_CONSTANT);
But the compilation will never allow you from invoking it in this way :
process("a not defined constant value");
Where should we declare the constants ?
If your application contains a single existing class that owns a specific and strong functional cohesion with the constant values, the 1) and the 2) appear more intuitive.
Generally, it eases the use of the constants if these are declared in the main class that manipulates them or that has a name very natural to guess that we will find it inside.
For example in the JDK library, the exponential and pi constant values are declared in a class that declare not only constant declarations (java.lang.Math).
public final class Math {
...
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
...
}
The clients using mathematics functions rely often on the Math class.
So, they may find constants easily enough and can also remember where E and PI are defined in a very natural way.
If your application doesn't contain an existing class that has a very specific and strong functional cohesion with the constant values, the 1 variant) and the 2 variant) ways appear more intuitive.
Generally, it doesn't ease the use of the constants if these are declared in one class that manipulates them while we have also 3 or 4 other classes that manipulate them as much as and no one of these classes seems be more natural than others to host constant values.
Here, defining a custom class to hold only constant values makes sense.
For example in the JDK library, the java.util.concurrent.TimeUnit enum is not declared in a specific class as there is not really one and only one JDK specific class that appear as the most intuitive to hold it :
public enum TimeUnit {
NANOSECONDS {
.....
},
MICROSECONDS {
.....
},
MILLISECONDS {
.....
},
SECONDS {
.....
},
.....
}
Many classes declared in java.util.concurrent use them :
BlockingQueue, ArrayBlockingQueue<E>, CompletableFuture, ExecutorService , ... and really no one of them seems more appropriate to hold the enum.
A: I use following approach:
public final class Constants {
public final class File {
public static final int MIN_ROWS = 1;
public static final int MAX_ROWS = 1000;
private File() {}
}
public final class DB {
public static final String name = "oups";
public final class Connection {
public static final String URL = "jdbc:tra-ta-ta";
public static final String USER = "testUser";
public static final String PASSWORD = "testPassword";
private Connection() {}
}
private DB() {}
}
private Constants() {}
}
Than, for example, I use Constants.DB.Connection.URL to get constant.
It looks more "object oriently" as for me.
A: Creating static final constants in a separate class can get you into trouble. The Java compiler will actually optimize this and place the actual value of the constant into any class that references it.
If you later change the 'Constants' class and you don't do a hard re-compile on other classes that reference that class, you will wind up with a combination of old and new values being used.
Instead of thinking of these as constants, think of them as configuration parameters and create a class to manage them. Have the values be non-final, and even consider using getters. In the future, as you determine that some of these parameters actually should be configurable by the user or administrator, it will be much easier to do.
A: The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.
Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth.
The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.
A: It is a BAD PRACTICE to use interfaces just to hold constants (named constant interface pattern by Josh Bloch). Here's what Josh advises:
If the constants are strongly tied to
an existing class or interface, you
should add them to the class or
interface. For example, all of the
boxed numerical primitive classes,
such as Integer and Double, export
MIN_VALUE and MAX_VALUE constants. If
the constants are best viewed as
members of an enumerated type, you
should export them with an enum
type. Otherwise, you should export the
constants with a noninstantiable
utility class.
Example:
// Constant utility class
package com.effectivejava.science;
public class PhysicalConstants {
private PhysicalConstants() { } // Prevents instantiation
public static final double AVOGADROS_NUMBER = 6.02214199e23;
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
public static final double ELECTRON_MASS = 9.10938188e-31;
}
About the naming convention:
By convention, such fields have names
consisting of capital letters, with
words separated by underscores. It is
critical that these fields contain
either primitive values or references
to immutable objects.
A: A Constant, of any type, can be declared by creating an immutable property that within a class (that is a member variable with the final modifier). Typically the static and public modifiers are also provided.
public class OfficePrinter {
public static final String STATE = "Ready";
}
There are numerous applications where a constant's value indicates a selection from an n-tuple (e.g. enumeration) of choices. In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved type-safety):
public class OfficePrinter {
public enum PrinterState { Ready, PCLoadLetter, OutOfToner, Offline };
public static final PrinterState STATE = PrinterState.Ready;
}
A: A single, generic constants class is a bad idea. Constants should be grouped together with the class they're most logically related to.
Rather than using variables of any kind (especially enums), I would suggest that you use methods. Create a method with the same name as the variable and have it return the value you assigned to the variable. Now delete the variable and replace all references to it with calls to the method you just created. If you feel that the constant is generic enough that you shouldn't have to create an instance of the class just to use it, then make the constant method a class method.
A: FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.
A: What is the difference
1.
public interface MyGlobalConstants {
public static final int TIMEOUT_IN_SECS = 25;
}
2.
public class MyGlobalConstants {
private MyGlobalConstants () {} // Prevents instantiation
public static final int TIMEOUT_IN_SECS = 25;
}
and using
MyGlobalConstants.TIMEOUT_IN_SECS wherever we need this constant. I think both are same.
A: I wouldn't call the class the same (aside from casing) as the constant ... I would have at a minimum one class of "Settings", or "Values", or "Constants", where all the constants would live. If I have a large number of them, I'd group them up in logical constant classes (UserSettings, AppSettings, etc.)
A: To take it a step further, you can place globally used constants in an interface so they can be used system wide. E.g.
public interface MyGlobalConstants {
public static final int TIMEOUT_IN_SECS = 25;
}
But don't then implement it. Just refer to them directly in code via the fully qualified classname.
A: For Constants, Enum is a better choice IMHO. Here is an example
public class myClass {
public enum myEnum {
Option1("String1", 2),
Option2("String2", 2)
;
String str;
int i;
myEnum(String str1, int i1) { this.str = str1 ; this.i1 = i }
}
A: One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.
A: static final is my preference, I'd only use an enum if the item was indeed enumerable.
A: I use static final to declare constants and go with the ALL_CAPS naming notation. I have seen quite a few real life instances where all constants are bunched together into an interface. A few posts have rightly called that a bad practice, primarily because that's not what an interface is for. An interface should enforce a contract and should not be a place to put unrelated constants in. Putting it together into a class that cannot be instantiated (through a private constructor) too is fine if the constant semantics don't belong to a specific class(es). I always put a constant in the class that it's most related to, because that makes sense and is also easily maintainable.
Enums are a good choice to represent a range of values, but if you are storing standalone constants with an emphasis on the absolute value (eg. TIMEOUT = 100 ms) you can just go for the static final approach.
A: I agree with what most are saying, it is best to use enums when dealing with a collection of constants. However, if you are programming in Android there is a better solution: IntDef Annotation.
@Retention(SOURCE)
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST,NAVIGATION_MODE_TABS})
public @interface NavigationMode {}
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
...
public abstract void setNavigationMode(@NavigationMode int mode);
@NavigationMode
public abstract int getNavigationMode();
IntDef annotation is superior to enums in one simple way, it takes significantly less space as it is simply a compile-time marker. It is not a class, nor does it have the automatic string-conversion property.
A: It is BAD habit and terribly
ANNOYING practice to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.
I have not read anything Joshua Bloch, so either
*
*he is a terrible programmer
*or the people so far whom I find quoting him (Joshua is the name of a boy I presume) are simply using his material as religious scripts to justify their software religious indulgences.
As in Bible fundamentalism all the biblical laws can be summed up by
*
*Love the Fundamental Identity with all your heart and all your mind
*Love your neighbour as yourself
and so similarly software engineering fundamentalism can be summed up by
*
*devote yourself to the ground-zero fundamentals with all your programming might and mind
*and devote towards the excellence of your fellow-programmers as you would for yourself.
Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn
*
*First love yourself. Because if you don't love yourself much, then the concept "love your neighbour as yourself" doesn't carry much weight, since "how much you love yourself" is the datum line above which you would love others.
Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.
The fundamental laws of software programming
*
*laziness is the virtue of a good programmer
*you are to make your programming life as easy, as lazy and therefore as effective as possible
*you are to make the consequences and entrails of your programming as easy, as lazy and therefore as effective as possible for your neigbour-programmers who work with you and pick up your programming entrails.
Interface-pattern constants is a bad habit ???
Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?
Just read the wikipedia article on interface-pattern constants (https://en.wikipedia.org/wiki/Constant_interface), and the silly excuses it states against interface-pattern constants.
*
*Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.
*
*Also - wait a second proponents of micro-functional programming as a means of not needing an IDE. Wait till you read my explanation on data-model normalization.
*Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion
*
*are not aware of, and the need for, data-model normalization
*Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of
*
*not seeing that "constants" must be treated as contract. And interfaces are used for enforcing or projecting compliance to a contract.
*It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???
*
*Why would you want to engage in such pattern of programming as your persistent livelihood? IOW, why devote yourself to such an AMBIVALENT and bad programming habit ?
Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.
It doesn't matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.
Similarly, I do not care what the "original" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don't care if I am perceived to "violate the intention for interfaces". I don't care what Gosling or someone Bloch says about the "proper way to use Java", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.
The Fundamental is Data-Model Normalization
It doesn't matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don't understand the need and process of data-model normalization.
We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.
Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.
A glaring flaw of EF Codd's and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.
The Fundamentals of Data Normalization
What EF Codd failed to express.
Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.
*
*The Unity and Identity of data instances.
*
*design the granularity of each data component, whereby their granularity is at a level where each instance of a component can be uniquely identified and retrieved.
*absence of instance aliasing. i.e., no means exist whereby an identification produces more than one instance of a component.
*Absence of instance crosstalk. There does not exist the necessity to use one or more other instances of a component to contribute to identifying an instance of a component.
*The unity and identity of data components/dimensions.
*
*Presence of component de-aliasing. There must exist one definition whereby a component/dimension can be uniquely identified. Which is the primary definition of a component;
*where the primary definition will not result in exposing sub-dimensions or member-components that are not part of an intended component;
*Unique means of component dealiasing. There must exist one, and only one, such component de-aliasing definition for a component.
*There exists one, and only one, definition interface or contract to identify a parent component in a hierarchical relationship of components.
*Absence of component crosstalk. There does not exist the necessity to use a member of another component to contribute to the definitive identification of a component.
*
*In such a parent-child relationship, the identifying definition of a parent must not depend on part of the set of member components of a child. A member component of a parent's identity must be the complete child identity without resorting to referencing any or all of the children of a child.
*Preempt bi-modal or multi-modal appearances of a data-model.
*
*When there exists two candidate definitions of a component, it is an obvious sign that there exists two different data-models being mixed up as one. That means there is incoherence at the data-model level, or the field level.
*A field of applications must use one and only one data-model, coherently.
*Detect and identify component mutation. Unless you have performed statistical component analysis of huge data, you probably do not see, or see the need to treat, component mutation.
*
*A data-model may have its some of its components mutate cyclically or gradually.
*The mode may be member-rotation or transposition-rotation.
*Member-rotation mutation could be distinct swapping of child components between components. Or where completely new components would have to be defined.
*Transpositional mutation would manifest as a dimensional-member mutating into an attribute, vice versa.
*Each mutation cycle must be identified as a distinct data-modal.
*Versionize each mutation. Such that you can pull out a previous version of the data model, when perhaps the need arise to treat an 8 year old mutation of the data model.
In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.
Are we still asking if we could use Interface Constants? Really ?
There are data-normalization issues at stake more consequential than this mundane question. IF you don't solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.
From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.
Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.
If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.
Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.
Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??
So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...
public interface CustomerService {
public interface Label{
char AssignmentCharacter = ':';
public interface Address{
String Street = "Street";
String Unit= "Unit/Suite";
String Municipal = "City";
String County = "County";
String Provincial = "State";
String PostalCode = "Zip"
}
public interface Person {
public interface NameParts{
String Given = "First/Given name"
String Auxiliary = "Middle initial"
String Family = "Last name"
}
}
}
}
Now I can reference my apps' contracted labels in a way such as
CustomerService.Label.Address.Street
CustomerService.Label.Person.NameParts.Family
This confuses the contents of the jar file? As a Java programmer I don't care about the structure of the jar.
This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.
Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named "Constants", because I don't want to have to search for constants and I am too lazy to repeatedly type "private final String".
public class PurchaseRequest {
private interface Constants{
String INTERESTINGName = "Interesting Name";
String OFFICIALLanguage = "Official Language"
int MAXNames = 9;
}
}
Perhaps even this:
public interface PurchaseOrderConstants {
public interface Properties{
default String InterestingName(){
return something();
}
String OFFICIALLanguage = "Official Language"
int MAXNames = 9;
}
}
The only issue with interface constants worth considering is when the interface is implemented.
This is not the "original intention" of interfaces? Like I would care about the "original intention" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???
After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "370"
} |
Q: .NET 3.5 Linq Datasource and Joins Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?
A: (EDIT misunderstood the question, revising my answer to the following)
Your LinqDataSource could point to a view, which allows you to overcome the problem of not being able to express a Join in the actual element. From "How to: Create LINQ to SQL Classes Mapped to Tables and Views (O/R Designer)":
The O/R Designer is a simple object relational mapper because it supports only 1:1 mapping relationships. In other words, an entity class can have only a 1:1 mapping relationship with a database table or view. Complex mapping, such as mapping an entity class to multiple tables, is not supported. However, you can map an entity class to a view that joins multiple related tables.
A: If the tables are connected by a foreign key, you can easily reference both tables as they will be joined by linq automatically (you can see easily if you look in your dbml and there is an arrow connecting the tables) - if not, see if you can add one.
To do that, you can just use something like this:
<%# Bind("unit1.unit_name") %>
Where in the table, 'unit' has a foreign key that references another table and you pull that 'unit's property of 'unit_name'
I hope that makes sense.
A: You cannot put more than one object/datasource on a datagrid. You will have to build a single ConceptObject that combines the exposed properties of the part Entities. Try to use DB -> L2S Entities -> ConceptObject. You must be very contrived if the DB model matches the ConceptObject field-for-field.
A: You are best using a ObjectDataSource when you wnt to do more complex Linq and bind your Grid to the ObjectDataSource.
You do however need to watch out for Anonymous types that could give you some trouble, but anything is posible...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why does Tomcat 5.5 (with Java 1.4, running on Windows XP 32-bit) suddenly hang? I've been running Tomcat 5.5 with Java 1.4 for a while now with a huge webapp. Most of the time it runs fine, but sometimes it will just hang, with no exception generated, and no apparant way of getting it to run again other than re-starting Tomcat. The tomcat instance is allowed a gigabyte of memory on the heap, but rarely exceeds 300 MB. Has anyone else run into this issue, and is there a solution for it?
For clarification: I determined how much memory it is using via Task Manager and via Eclipse (I've also tried running it outside of Eclipse, but get the same problem eventually, though it takes a little longer). With Eclipse, I look at the memory allocated via its little (optional) memory pane and the amount allocated to javaw.exe via the task manager. I use the sysdeo? tomcat plugin for Eclipse.
A: For any jvm process, force a thread dump. In windows, this can be done with CTRL-BREAK, I believe, in the console window.
In *nix, it is almost always "kill -3 jvm-pid".
This may show if you have threads waiting on db connection pool/thread pool, etc.
Another thing to check out is how many connections you have currently to the JVM -- either use NETSTAT or SysInternals utility such as tcpconn/tcpview (google it).
Also, try to run with the verbose:gc JVM flag. For Sun's JVM, run like "java -verbose:gc". This will show your garbage collections. If it is collecting a lot (FULL COLLECTIONS, expecially) then you probably have a memory leak. The full collections are costly, especially on large heaps like that.
How are you determining that only 300mb are being used?
A: It sounds like you're hitting a deadlock.
If you can reproduce it in a dev environment then try attaching a debugger once it's happened. Take a look at your threads and see if you have any deadlocks.
If you can't get a debugger to attach you should be able to generate a thread dump, as Dustin pointed out.
A: Try increasing the logging sensitivity for the Tomcat application server.
http://tomcat.apache.org/tomcat-5.5-doc/logging.html
You can increase the sensitivity to FINEST or ALL for most of them for a few days and see if that helps you catch anything.
A: I agree with creating multiple thread dumps and viewing them though this: Thread Dump Analyzer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to identify specific digits of an integer input in C? I need to get the number of digits containing the number 1. I know in java I can take the input as a String and use charAt, but I understand there is no implicit String function in C. How can I accomplish this?
A: Division and modulus are your friends.
#include "stdio.h"
int main(){
int digits[] = {0,0,0,0,0,0,0,0,0,0};
int i = 11031;
while(i > 0){
digits[i % 10]++;
i = i / 10;
}
printf("There are %d ones.\n", digits[1]);
}
A: Homework?
You'd read it into a char* using the fread() function, and then store how many bytes were read in a separate variable. Then use a for loop to iterate through the buffer and count how many of each byte are present.
A: If you have just the number, then you can do this:
int val; //Input
...
int ones = 0;
while(val != 0) {
ones += ((val % 10) == 1) ? 1 : 0;
val /= 10;
}
If you have a string (char*), the you'd do something like this:
while(*str != '\0') {
if(*str++ == '1') {
ones++;
}
}
It's also worth noting that c does have a charAt function, in a way:
"java".charAt(i) == "c the language"[i];
By indexing into the char*, you can get the value you want, but you need to be careful, because there is no indexOutOfBounds exception. The program will crash if you go over the end of a string, or worse it may continue running, but have a messed up internal state.
A: Try something like...
int digit = 0;
int value = 11031;
while(value > 0)
{
digit = value % 10;
/* Do something with digit... */
value = value / 10;
}
A: I see this as a basic understanding problem, which inevitably everyone goes through switching from one language to the next.
A good reference to go through to understand how string's work in C when you've started familiarity with java is look at how string.h works. Where as in java string's are an Object and built in, strings in C are just integer arrays.
There are a lot of tutorials out there, one that helped me when I was starting earlier in the year was http://www.physics.drexel.edu/students/courses/Comp_Phys/General/C_basics/ look at the string section.
Sometimes asking a question speeds up learning a lot faster than pouring through the text book for hours on end.
A: Something along the lines of:
int val=11031;
int count=0;
int i=0;
char buf[100];
sprint(buf, "%d", val);
for(i=0; (i < sizeof(buf)) && (buf[i]); i++) {
if(buf[i] == '1')
count++;
}
A: int count_digit(int nr, int digit) {
int count=0;
while(nr>0) {
if(nr%10==digit)
count++;
nr=nr/10;
}
return count;
}
A: This sounds like a homework problem to me. Oh well, it's your life.
You failed to specify the type of the variable that contains the "input integer". If the input integer is an integral type (say, an "int") try this:
int countOnes(int input)
{
int result = 0;
while(input) {
result += ((input%10)==1);
result /= 10;
}
return result;
}
If the "input integer" is in a string, try this:
int countOnes(char *input)
{
int result = 0;
while(input && *input) {
result += (*input++ == '1');
}
return result;
}
Hope this helps. Next time, do your own homework. And get off of my lawn! Kids, these days, ...
A: int countDigit(int Number, int Digit)
{
int counter = 0;
do
{
if( (Number%10) == Digit)
{
counter++;
}
}while(Digit>0)
return counter;
}
A: Something along the lines of this:
#include <stdio.h>
main() {
char buf[100];
char *p = buf;
int n = 0;
scanf("%s", buf);
while (*p) {
if (*p == '1') {
n++;
}
p++;
}
printf ("'%s' contains %i ones\n", buf, n);
}
A: This will do it. :-)
int count_digits(int n, int d) {
int count = 0;
while(n*10/=10) if (n%10==d) count++
return count;
}
A: For all those who refer to the question as the homework question: I have to say, most of you provided a homework answer.
You don't do division/modulus to get the digits in production code, firstly because it's suboptimal (your CPU is designed for binary arithmetics not decimal) and secondly because it's unintuitive. Even if it's not originally a string, it's more optimal to convert it to one and then count the characters (std::count is the way to go in C++).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XWindow ignores multiple ClentMessage's sent during same second I've encountered an interesting problem while developing for our legacy XWindows application.
For reasons that don't bear explaining, I am sending ClientMessage from a comand-line utility to a GUI app.Most of the messages end up having the same contents, as the message's purpose is to trigger a synchronous communication process over some side pipes. I've noticed that some of the time I would send two messages, but only one gets delivered. I've traced this to the fact that both messages had the same contents and were sent in the same second (IOW, the log timestamp on the sending was the same number). As soon as I added some dummy contents to the messages to make them all different, the problem went away.
This happened over two different X servers: vncserver and Exceed. Am I hitting some XWindows feature that I am not aware of - some kind of message throttling/compression? Has anyone encountered this kind of thing?
A: The X server should never compress client messages that I'm aware of, but perhaps some X toolkits (Motif, Xaw, etc.) do compress them. That's the first thing I would look for - perhaps the GUI app receiving the message is compressing somewhere inside the toolkit, before the application code sees it.
Then again, both vncserver and exceed probably focus more on remote usage than other X servers, and they could contain some ill-advised compression hacks, conceivably. I have read a lot of X specs and written a lot of X code and never heard of this behavior though.
A random unlikely thought, be sure you have an XFlush() or XSync() at the end of your command line app before it exits, to be sure you write those messages out to the socket before closing down. But I don't know why message content would matter if this is the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET - Common Gotchas When I am working with ASP.NET, I find that there are always unexpected things I run into that take forever to debug. I figure that having a consolidated list of these would be great for those "weird error" circumstances, plus to expand our knowledge of oddness in the platform.
So: answer with one of your "Gotcha"s!
I'll start:
Under ASP.NET (VB), performing a Response.Redirect inside a try/catch block does not stop execution of the current Response, which can lead to two concurrent Responses executing against the same Session.
A: Viewstate ... if you are using it ... can get out of control if you are not paying attention to it.
A: The whole life-cycle thing in general.
Not that I see anything wrong with it, it's just that you'd be amazed at the number of people who start working on large ASP.Net projects before understanding it, rather than vice versa. Hence, it becomes a gotcha.
Note that I said large projects: I think the best way to come to terms with the life cycle is to work on a few smaller projects yourself first, where it doesn't matter so much if you screw them up.
A: Life cycle of custom controls does not match up perfectly with page life cycle events of same name.
A: Page_Load is run before control handlers. So you can't make changes in an event handler and then use those changes in the page load. This becomes an issue when you have controls in a master page (such as a login control). You can get around the issue by redirecting, but it's definitely a gotcha.
A: Having to jump through hoops to get the .ClientID property into javascript.
It'd be nice if the render phase of the lifecycle created a script that set up a var for each server control with the same name as the control that was automatically initialized to the clientID value. Or maybe have some way to easily trigger this action.
Hmm... I bet I could set up a method for this on my own via reflection.
A: Don't edit your web.config with notepad if you have accented characters, it will replace it with one with the wrong encoding. It will look the same though. Just your application will not run.
A: I just learned this today: the Bind() method, as used with GridViews and ListViews, doesn't exist. It's actually hiding some Reflector magic that turns it into an Eval() and some kind of variable assignment.
The upshot of this is that calls like:
<%# FormatNameHelper(Bind("Name")) %>
that look perfectly valid will fail. See this blog post for more details.
A: Debugging is a very cool feature of ASP.Net, but as soon as you change some code in the app_code folder, you trigger a re-build of the application, leading to all sessions being lost.
This can get very annoying while debugging a website, but you can easily prevent this using the "StateServer mode" : it's just a service to start and a line to change in the web.config :
refer to msdn : http://msdn.microsoft.com/en-us/library/ms178586.aspx
*
*InProc mode, which stores session state in memory on the Web server. This is the default.
*StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
*SQL Server ...
*Custom ...
*Off!
A: Don't dynamically add controls after the page init event as it will screw up the viewstate tree.
A: If you are running Classic ASP applications in the same Virtual Directory as you ASP.Net application, the fist hit on the application must be on an ASP.Net page. This will ensure that the AppPool be built with the right context configurations. If the first page to be hit is a Classic ASP page, the results may vary from application to application. In general the AppPool is configured to use the latest framework.
A: Making a repeater-like control, and not knowing about INamingContainer.
A: *
*You have to worry about session timeouts for applications where the user might take a long time.
*You also have to worry about uploading timeouts for large applications, too
*Validatiors may not always scroll your page to the scene of the data entry error (so the user may not ever see it and will only wonder why the submit button won't work )
*If the user enters HTML symbols such as <, > (for example, P > 3.14 ), or an inadvertant <br> from copy-pasting on another page, ASP.NET will reject the page and display a error.
*null.ToString() produces a big fat error. Check carefully.
*Session pool sharing across multiple applications is a disaster silently waiting to happen
*Moving applications around on machines with different environments is a migraine that involves web.config and many potential hours of google
*ASP.NET and MySQL are prone to caching problems if you use stored procedures
*AJAX can make a mess, too:
*
*There are situations where the client can bypass page validation (especially by pressing ENTER instead of pressing the submit button). You can fix it by calling if(! Page.IsValid) { return ; }
*ASP buttons usually don't work correctly inside of UpdatePanels
*The more content in your UpdatePanel, the more data is asynchronously transmitted, so the longer it takes to load
*If your AJAX panel has a problem or error of some kind, it "locks up" and doesn't respond to events inside it anymore
A: Custom controls are only supported by the designer when building the control or when building the page that uses the control, but not both.
A: When using a gridview without a datasource control (i.e. binding a dataset straight to the control) you need to manually implement sorting and paging events as shown here:
http://ryanolshan.com/technology/gridview-without-datasourcecontrol-datasource/
A: Linq: If you are using Linq-To-SQL, you call SubmitChanges() on the data context and it throws an exception (e.g. duplicate key or other constraint violation), the offending object values remain in your memory while you are debugging, and will be resubmitted every time you subsequently call SubmitChanges().
Now here's the real kicker: the bad values will remain in memory even if you push the "stop" button in your IDE and restart! I don't understand why anyone thought this was a good idea - but that little ASP.NET icon that pops up in your system tray stays running, and it appears to save your object cache. If you want to flush your memory space, you have to right-click that icon and forcibly shut it down! GOTCHA!
A: You can't reference anything at all above the application's root folder.
A: All the code I have to maintain that still looks like it was written in vb6, showing complete ignorance of the newer styles.
I'm talking things like CreateObject(), excessive <% %> blocks, And/Or instead of AndAlso/OrElse, Len() instead of .Length(), s/o Hungarian prefix warts, Dim MyVariable with no type, functions with no return type... I could go on.
A: Being unaware of heaps of existing and extensible functionality in the framework. Things often redone are membership, roles, authorization, site maps. Then there are the controls and the associated tags which can be customized to alleviate issues with the client IDs among others. Also simple things like not knowing to properly use the .config file to auto import namespaces into templates, and being able to do that on a directory basis. Less known things like tag expressions can be valuable at times as well. Surely, as with all frameworks, there is a learning curve and always something left to be desired, however more often than not it is better to customize and extend an existing framework instead of rolling your own.
A: Not a pure ASP.NET thing, but ...
I was trying to use either a) nested SELECT or b) WITH clause and just could not get it to work, but people who were obviously more knowledgeable (including someone I work with) told me the syntax was fine. TURNS OUT ...
Was not able to use either of those with OLEDB.
OLEDB query to SQL Server fails
(Also, I was bit by the response.redirect() in the try ... catch 'feature' mentioned in the OP! Great thread!)
A: Databound controls inside an INamingContainer control must not be placed inside templated controls such as FormView. See this bug report for an example. Since INamingContainer controls creates their own namespace for their contained controls, two-way databinding using Bind() will not work properly. But when loading the values everything will look fine (because it is done with Eval()) it is not before you try to post back the values that they will mysteriously seem to not land in the database.
This so question demonstrates the issue well: AJAX Tabcontainer inside formview not inserting values
A: (VB.NET) If you send an Object via a Property's Get accessor into a function with a ByRef keyword, it will actually attempt to update the object using the Set accessor for the Property.
Ex:
UpdateName(ByRef aName as String)
UpdateName(Employee.Name) will attempt to update the name by using the Set on the Name property of Employee.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Is there a user friendly XML editor out there? I can't find anything good, preferably open source Something to take an XML schema and let you add/edit data but not change the XML structure, preferably installed on a server. basically a UI to edit xml documents as a web app. Someone has got to have done this already right?
A: Xopus is a commercial XML editor designed specifically to be used by non-technical people. Xopus is browser based and can be installed on any webserver. Xopus keeps the XML document 100% valid at all times using XML Schema and has a WYSIWYG view using XSLT.
You could use the DOM API to configure it so that only the text can be changed, not the structure.
Direct link to a demo.
A: Liquid XML have a nice free version
update: (as of March 10 2010) it seems that the editor is no longer free
A: IMHO BXE - The Wysiwyg XML Editor can do this - i.e. create/edit XML document in browser, based on existing XML Schema.
I am not sure, but you probably have to include it in your own page, it is just the editor component, not the full web application.
A: It depends on what you mean by "user friendly", and what you want out of a text editor. I personally use emacs for editing xml, but I'm willing to put up with the learning curve of the editor for the sheer power it gives me - editing XML is now rather easy and painless for me, but it took me a bit to get it to that point.
oXygen looks like it might fit what you want, but it's not free.
This page has a good comparison of xml editors and there features, seems like a good starting point.
A: XML Copy Editor is free and GPL
A: Check out microsoft for an XML Notepad 2007. I'm not to fond of it, since it really treats xml as a tree as opposed to plain text, but that is what you want, right?
A: I personally like Notepad++ with the XMLTools plugin.
It will unfortunately allow you to edit the structure.
A: I don't think there is a web-app that allows you to write an instance document based on an uploaded schema (as yet.. mebbe I should write one? :) ).
Altova XMLSpy is pretty much the best of the editors I have used, but very expensive.
A: Give vim a try with a suitable plugin (http://www.vim.org/scripts/script.php?script_id=301).
/Allan
A: What about Eclipse with the Oxygen plugin, that would be my recommendation, free open source and very widely used. Altova XML Spy is a great tool but expensive, they used to do a free non-commercial use edition but that doesn't appear on their website now so perhaps they have discontinued that.
A: XML Editor is free (whereas the various FO converters are not) and you can use it with FOP (from the Apache project). Emacs with the psgml module can do it along with vim but both probably more low-lovel). Eclipse can do it too but iut is rather heavyweight.
A: If you just want an XML editor with code folding and a node explorer (something Visual Studio is missing) Netbeans has both, and is free and open source
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to write an SQL query to find out which logins have been granted which rights in Sql Server 2005? I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on SQL Server 2005.
I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the sysadmin role on their login - it was a single line query for the latter.
But how to find out which logins have a User Mapping to a particular (or any) database?
I can find the sys.database_principals and sys.server_principals tables. I have located the sys.databases table. I haven't worked out how to find out which users have rights on a database, and if so, what.
Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?
A: Check out this msdn reference article on Has_Perms_By_Name. I think you're really interested in examples D, F and G
Another idea... I fired up SQL profiler and clicked on the ObjectExplorer->Security->Users. This resulted in (approx) the following query being issued.
SELECT *
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp
ON dp.grantee_principal_id = u.principal_id and dp.type = N'CO'
WHERE (u.type in ('U', 'S', 'G', 'C', 'K'))
ORDER BY [Name] ASC
A:
select * from Master.dbo.syslogins l inner join sys.sysusers u on l.sid = u.sid
This will get you what users are mapped to which logins within a single database.
A: Here's how to do this. I ended up finding reference to a sproc in the MSDN docs. I pulled this from the sproc and wrapped it in a loop of all the databases known to the instance.
select DbRole = g.name, MemberName = u.name
from @NAME.sys.database_principals u, @NAME.sys.database_principals g, @NAME.sys.database_role_members m
where g.principal_id = m.role_principal_id
and u.principal_id = m.member_principal_id
and g.name in (''db_ddladmin'', ''db_owner'', ''db_securityadmin'')
and u.name not in (''dbo'')
order by 1, 2
This then reports the users that have DBO who perhaps shouldn't. I've already revoked some admin access from some users that they didn't need. Thanks everyone!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's happening with Perl 6? Is there any visible progress? Is it now just an academic exercise? Do you believe Perl will continue to evolve with or without Perl 6 or will soon be forgotten?
A: Please see the Official Perl 6 Wiki to find the latest information:
http://www.perlfoundation.org/perl6/index.cgi?perl_6
The latest headlines from 2 leading Perl 6 blogs are shown at the bottom of the official Perl 6 wiki home page.
There's lots of other useful information and links there.
For example, recent Perl 6 articles and presentations:
http://www.perlfoundation.org/perl6/index.cgi?perl_6_articles_and_presentations
The Parrot VM for dynamic languages (to be used by Rakudo/Perl 6) also has an official wiki:
http://www.perlfoundation.org/parrot/index.cgi?parrot
Parrot is multi-lingual, so Perl 6 will be able to call modules written in other Parrot languages, and other Parrot languages will be able to call Perl 6 modules compiled to Parrot.
Unlike Perl 5, which is defined by its reference implementation, Perl 6 is defined by its test suite. So there will eventually be other versions of Perl 6 that don't run on the Parrot VM.
Perl 5 is still evolving. Perl 5.10 was a major recent release, which (among many other improvements) also had a few Perl 6 related features. Perl 5.12 is under active development (as Perl 5.11).
Perl 5.12 will have support for calling (and for being called by) Perl 6. Perl 6 should be able to compile the great majority of Perl 5 code -- this is a major priority.
Please see the Official Perl 5 Wiki to find the latest information:
http://www.perlfoundation.org/perl5/index.cgi?perl_5_wiki
A: Perl 6 is moving along nicely. Perl 6 is a bit unlike previous Perl's in that Perl 6 is actually a language specification not an implementation of it. The reference implementation on top of Parrot that is the main thrust of the Perl 6 project has been renamed Rakudo and is moving along nicely. The best place I've found for news about it is http://planetsix.perl.org/. Currently, as far as I understand it, most of the important features of the language are implemented and they are fleshing out the rest and writing tests. You can download it and test it out a bit. The easiest way seems to be the cygwin version which has been bundled up and made into a cygwin package.
A: There is now a roadmap for parrot at least.
There is also a website that tracks the number of tests that the Rakudo implementation passes.
(source: rakudo.de)
A: The ability to target other languages to the parrot vm, will make it trivial to make a product using what ever languages you are comfortable with.
List of languages with recent activity, or at least tested with latest parrot (as of 2008/09/22):
taken from languages/LANGUAGES_STATUS.pod
*
*APL
*bf
*Cardinal (Ruby)
*Chitchat (Smalltalk)
*Cola (Java)
*Common Lisp
*Eclectus (Scheme)
*ECMAScript
*HQ9+
*Jako (C/Perl)
*JSON
*lazy-k
*lolcode
*Lua
*Parrot m4
*Markdown
*NQP (Not Quite Perl)
*Rakudo
*Pheme (Lisp-2 compiler inspired by Scheme)
*Pipp (Pipp is Parrot's PHP)
*PJS (wiki)
*Punie (Perl1)
*regex
*Squaak (Squaak is not Squeak)
*partcl (TCL)
*unlambda
*WMLScript Translator
A: Perl 5 will continue to be wonderful and available even if Six never comes to fruition. Six invigorated Perl 5, and Perl 5 continues to experience many wonderful new things, such as Moose.
I think Perl 6 will be completed some day and will be good, but for now, I'm a Fiver, and I'm happy like that.
A: To the comment that it didn't start until 2005... I suppose it depends on if you count Parrot as Perl6. The original team did, but we didn't get buy in from the "Perl6 Language" folks for years.
We were doing real work on Parrot in 2000-2004 and much of the VM groundwork was there. By 2002 we had continuations, co-routines, a JIT, an intermediate compiler and a dozen languages besides Perl6, including a BASIC interpreter written in Parrot's PIR. By then we could compile and run pretty much any sort of language in the world, short of highly concurrent languages, and our capability far exceeded the needs of Perl6 for an implementation platform.
The VM itself has been capable for years. Perl6 as a language is a different story since it is a very complex beast to parse. That has no reflection on Parrot. It is simply a reflection on the culture of Perl and it is why the rise of other scripting languages has accelerated and Perl5 is in decline and people who once chose Perl5 for new systems implementation moved to Ruby, Python and Groovy, and languages like Java and C# evolved frameworks that make a heavy use of reflection for runtime dispatching.
As much as I love Perl, if a language is so difficult to implement that a production quality compiler cannot be written in less than a decade, something is wrong! C++ is easier to parse and was implemented in a fraction of the time of Per6. That should tell us something. Derek Jones writes in his blog "The Shape of Code" that C++ may have gotten "Too Big to Fail" (http://shape-of-code.coding-guidelines.com/2008/12/c-goes-for-too-big-to-fail/). C++ can afford to do that since it got successful first before it got big. Perl6 may be "Too Big to ever Succeed" because the scope was so grandiose that the project has trouble retaining contributors due to the fact that the attention span of the typical contributor is probably 2-3 years, not 10.
A: I feel like some good things may come from Perl 6 (e.g. parrot), but I'm not counting on ever doing anything with the language.
In the bioinformatics development group where I work, we're encouraging use of Python for new development where Perl would have been the language of choice in the past. Python appears to provide a better path forward for us.
A: At the risk of sounding like a Perl fanboy, I'm still excited about Perl 6 and feel like the end result will be relevant when it's released. The last nine months have yielded some nice accomplishments on the Parrot front () and have even resulted in some sizable donations to help fund increased development.
From a recent blog post:
Rakudo currently supports arrays, hashes, classes, objects, inheritance, roles,
numeration types, subset types, role composition, multimethod dispatch, type checking, basic I/O, named regular expressions, grammars, optional parameters, named parameters, slurpy parameters, closures, smart match, junctions, and many other features expected from Perl 6.
Keep your eye on Rakudo.org (Rakudo is the name of the Perl 6 implementation built on top of Parrot) for news on the ongoing development process of Perl 6.
A: You should not forget that Perl 5 is being developed in parallel. 5.10 was out not so long ago with new features and additions to the language.
Progress on Perl 6 is slow but steady, PUGS (Perl 6 over Haskell ) has been stalled for a while but Audrey might resume workingon it soon. In the mean while Rakudo (Perl 6 over parrot) is progressing well. Here is a post detailing various implementations progress
Realistically I would not hold my breath for it but no matter how late it will be I think when it comes out it will still be relevant.
A: Perl 6 is evolving slowly but steadily. Larry Wall wrote a Parser that can parse all Perl 6 that we know of (which is basically the test suite plus a bit of other code). Rakudo, which is Perl 6 on Parrot, also performs nicely. You can track its progress in the test suite with the charts on rakudo.de
Note that it's a radically new language, and not trivial to implement. I don't expect a usable version before next year, and even then it will take quite some time for any implementation to become as mature as Perl 5 is today (which has had 20 years to develop a stable code base).
A: There is plenty of visible progess. chromatic posts the minutes from the weekly Parrot/Perl 6 conference call to Use.perl and rakudo.org each week, you can read Jonathan Worthington's journal, or Patrick Michaud's journal, or the various Perl 6 mailing lists. As Mortiz points out, you can see the daily state of the test suite.
Recent developments include Larry Wall's finishing off the work to specify the complete grammar, the Rakudo developers adding pre-compiled module support, and Jonathan's multi-level dispatch work.
It's certainly easy to follow the progress, but you probably already knew that you could easily use Google to find out ("perl6 progress" leads to good resources). Perhaps you had another question though, or just want to kick the hornet's nest?
A: Slow and late. It has a terminal case of second system disease. When I was a Perl hacker (back in the day), they had been working on Perl 6 for two years. That was 6 years ago. You could build a whole operating system in that time.
A: It'll be out by Christmas. ;-) I've heard on podcasts that there there will be some kind of alpha before this Christmas. They were explicit about that but it has been a while since I heard that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: C++ web service framework We are looking for a C++ Soap web services framework that support RPC, preferably open source.
Any recommendations?
A: http://code.google.com/p/staff/
Staff is Web Service Framework for C++ (service/component and client-side)/JavaScript(client-side) based on Apache Axis2/C.
Open-source, released with Apache License V2.0.
A: Try the ffead-cpp framework, it provides in-built web-service support, rest, json and many other useful features.
A: WSO2 Web Services Framework for C++ (WSO2 WSF/C++), a binding of WSO2 WSF/C into C++ is a C++ extension for consuming Web Services in C++.
http://wso2.org/projects/wsf/cpp
Apache Axis is an open source, XML based Web service framework. It consists of a Java and a C++ implementation of the SOAP server, and various utilities and APIs for generating and deploying Web service applications.
http://ws.apache.org/axis/
A: We are using EasySoap (http://easysoap.sourceforge.net/)
A: While not FOSS another library is ATL Server library from Microsoft.
It is C++ template based with some proprietary attributes by Microsoft. i.e. not standard C++
A: You can check out xmlbeansxx. This is a kind of lightweight, low level solution, compared to complete frameworks. This has advantages in some cases.
Invoking SOAP WebServices using xmlbeansxx Article
Code example is here:
WsClient.cpp.
A: You could try gSOAP. Available under GPL and commercial licences.
A: I have used SWIG to make an interface from C++ to Java or Python and then used the typical web interface support for those languages.
Since Java and Python have reflection the web services frameworks that exist for them have a much easier time passing data around.
Threading wise if your C++ code is thread safe you can let the Java server manage the creation of threads for concurrent requests etc. and just call into your C++ code using JNI.
As a bonus you can test your C++ code from Python using these same SWIG interfaces.
A: I think the way to go is to write your service in C++ (I am assuming you did all the homework and there is a good reason you want to write in C++) and then front it using an RPC server. Use something like Thrift or Protobufs for a fast RPC implementation.
Now write your web frontend in the language of your choice - python would be mine - and make RPC calls to do all your heavy lifting.
A: POCO Remoting gives you a very simple way of creating web services in C++ by just annotating C++ class definitions with special comments and running a code generator over it. It's commercial, but delivered with full source code. A free eval version is available. Runs on Windows, Linux, Mac OS X, etc.
A: I concur with imjorge's answer and add that there's a C/C++ version of the Axis2 framework (a more flexible, extensible Axis) that does SOAP via RPC and all sorts of stuff including a bunch of the WS-* specs.
http://ws.apache.org/axis2/c/
A: Apache axis-c:
Simple to use, but seems abandoned.. not even download pages is working for several months
WSOF WSFCPP:
Fast quickstart dev, both binded or no-binded implementation, based on Apache AxisC and it seems most of the current developers of Apache Axis is from WSOF company. Besides the Great potential I've detected a memory leak.
I'm currently using Gsoap and It has very good performance.
Gsoap "mixed notation" between old c style and some (bad?) practices for C++ bothers me some.. but this is only code-furniture.
POCO:
Is a full-feature, modern (java?) like library. It is open source software, licensed under the Boost Software License 1.0. You'll have to write some things from scrach, but with great support, utility classes and etc great library.. Innovations from c++11+ with all boost initiatives + POCO + a new Build/Dependency system more "gradle like" will certainly bring c++ to new areas of development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Krypton Controls anyone? I found the ad on this site to Krypton controls (and here's another one!) and was wondering if any of you using vs.net 05 or 08 are using them and how that's working out. If you're answering, please specify which parts you're using (free, ribbons, tabs) and which vs.net you're on, which language(s) you use, along with pros and cons. I know there are probably better suites out there that you may be fond of, but this question is specifically about Krypton controls. We'd be using it with vb.net, .net 3.5, 08, so I'm particularly interested in hearing about your experience in those areas. (I've watched all the screencasts)
A: I have been using the free controls in various small internal projects for work for several years. I started following his blog just as he started as MicroISV, from a mention on a MicroISV blog. So I have been through many improvments he has made. The controls he makes are rock solid (at least in my usage of them) and he really listens to what his users want in features and other controls.
I HIGHLY recommend the controls!
A: I have been using the full suite for the last year and a half. I have been very happy with the results. They are easy to use and I haven't run into any issues that I couldn't fix myself (I purchased the source code version).
Definitely recommended.
A: I have been using the Krypton Controls ToolKit for over 3 years with Visual Studio 2005 and 2008 in .NET 2.0, 3.0, 3.5, and 3.5 SP1. I have only used the free ToolKit and not the Ribbon or Tab controls. I have used it only in C#.
Pros:
*
*Free
*Easy to Use - It adds all of the components to the Toolbox so it's very easy to implement.
*The font rendering is awesome compared to the default windows form controls.
*The "chrome" which allows you to totally override the look of the application is very nice.
*The ability to define a master scheme makes it easy to change the look of similar controls in one central location.
*The support, even on the free Toolkit is awesome, by submitting questions on the Component Factory forum.
*It includes additional controls that should've been part of the windows form controls including headergroups.
Cons:
*
*That the other components aren't free ;)
*In older versions, some controls didn't exist in the ToolKit so you had to use the winform control which wouldn't entirely fit with the application look. The latest version, however, has most, if not all the controls implemented as Krypton controls.
Here's a quick sample of our options dialog for the "MuvEnum Address Bar" using the Krypton Chrome. It was super easy to create. Notice the smoothness of the fonts.
I can't recommend the Krypton Controls enough.
John Rennemeyer
MuvEnum
A: I'm using it. It's quite okay.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Lightweight REST library for Java I'm looking for a light version of REST for a Java web application I'm developing.
I've looked at RESTlet (www.restlet.org) and the REST plugin for Struts 2, but I haven't made up my mind. I'm leaning towards RESTlet, as it seems to be lighter.
Has anyone implemented a RESTful layer without any of the the frameworks or with the frameworks?
Any performance issues that you've seen because of the new web layer?
Did the introduction of REST added unmanageable or unreasonable complexity to your project? (Some complexity is understandable, but what I mean is just plain overkilling your design just to add REST)
A: I'm a big fan of Restlet, but I usually use it to implement apps whose primary role is to be a RESTful web service. It sounds like you're looking to add a RESTful API to an existing application. If that's the case, JAX-RS's (or Enunciate's) annotation-based approach might be a better fit for your project.
As for Restlet, I can tell you that I've been very impressed with the developers and the community; they're very active, engaged, responsive, and committed to a stable, efficient, reliable, and effective framework. My single favorite aspect of the framework is that it is a ground-up implementation of the REST paradigm; therefore there is no impedance-mismatch between a Restlet app's external API and internal implementation. I also really like how flexible it is - it can run inside a Java application container/server such as JBoss, Tomcat, Jetty, etc, or standalone, with an embedded HTTP server library.
A: Well, I've used Enunciate quite a bit. It uses simple annotations to provide either REST and/or SOAP endpoints.
http://enunciate.codehaus.org
Plus, Ryan Heaton has always provided top-notch support for things, too.
A: You know there is a new JCP API for Accessing RESTful Services, also:
JAX-RS JCP311
https://jsr311.dev.java.net/
The open source version is called Project Jersey
A: I'm a huge fan of JAX-RS - I think they've done a great job with that specification. I use it on a number of projects and its been a joy to work with.
JAX-RS lets you create REST resources using POJOs with simple annotations dealing with the URI mappings, HTTP methods and content negotiation all integrated nicely with dependency injection. There's no complex APIs to learn; just the core REST concepts (URIs, headers/response codes and content negotiation) are required. FWIW JAX-RS is quite Rails-ish from the controller point of view
There are a number of JAX-RS implementations out there - see this thread for a discussion.
My personal recommendation is to use Jersey as its got the biggest, most active community behind it, has the best features at the time of writing (WADL support, implicit views, spring integration, nice REST client API); though if you are using JBoss/SEAM you might find RESTeasy integrates a little better.
A: I am working on a REST API for gliffy.com and we ended up rolling our own. We didn't want to have to bring in Struts 2, Spring, or any other framework. I looked at RESTLet and found it incredibly confusing and over complicated.
Apache has an implementation of the JAX-RS spec, but it is not finalized and also has some oddities to it. We're tentatively planning to open source our solution, but that's not for a few months.
Rolling your own is easy, though. The Servlet Specification gives you everything you need, and you can easily connect to a database via Hibernate (see http://www.naildrivin5.com/daveblog5000/?p=39 for how to set up JPA without using EJB3).
A: I found restlet to be a really elegant architecture. I'm working in the .net world so it was not an option for me, but I was able to build my own framework following the same basic principles of restlet.
I have found the conversion of our WCF contract-based SOA application to REST based one has significantly simplified the application,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Image Misalignment in Visual Studio application I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.
What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?
A: We found a solution! Apparently the picture boxes stretched out on the Chinese XP PC, but the images they contained did not. The fix was to add code like the following:
Me.PictureBoxIcon.Width = Me.PictureBoxIcon.Image.Width
Me.PictureBoxIcon.Height = Me.PictureBoxIcon.Image.Height
Dim loc As New Point
loc.X = Me.PictureBoxIcon.Location.X
loc.Y = Me.PictureBoxIcon.Location.Y + Me.PictureBoxIcon.Height
Me.PictureBoxAbout.Location = loc
Me.PictureBoxAbout.Width = Me.PictureBoxAbout.Image.Width
Me.PictureBoxAbout.Height = Me.PictureBoxAbout.Image.Height
Hope this helps someone else!
A: In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at the top left with the first and assuming an array with the images in order:
images[0].Location = new Point(0,0);
for (int i = 1; i < images.Length; i++)
{
images[i].Location = new Point(images[i - 1].Location.X + images[i - 1].Width, 0);
}
That will set the first image to the top left corner and all subsequent images to just after the last image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Perl aids for regression testing Is there a Perl module that allows me to view diffs between actual and reference output of programs (or functions)? The test fails if there are differences.
Also, in case there are differences but the output is OK (because the functionality has changed) I want to be able to commit the actual output as future reference output.
A: As mentioned, Test::Differences is one of the standard ways of accomplishing this, but I needed to mention PerlUnit: please do not use this. It's "abandonware" and does not integrate with standard Perl testing tools. Thus, for all new test modules coming out, you would have to port their functionality if you wanted to use them. (If someone has picked up the maintenance of this abandoned module, drop me a line. I need to talk to them as I maintain core testing tools I'd like to help integrate with PerlUnit).
Disclaimer: while Id didn't write it, I currently maintain Test::Differences, so I might be biased.
A: I tend to use more of the Test::Simple and Test::More functionality. I looked at PerlUnit and it seems to provide much of the functionality which is already built into the standard libraries with the Test::Simple and Test::More libraries.
A: I question those of you who recommend the use of PerlUnit. It hasn't had a release in 3 years. If you really want xUnit-style testing, have a look at Test::Class, it does the same job, but in a more Perlish way. The fact that it's still maintained and has regular releases doesn't hurt either.
Just make sure that it makes sense for your project. Maybe good old Test::More is all you need (it usually is for me). I recommend reading the "Why you should [not] use Test::Class" sections in the docs.
A: For testing the output of a program, there is Test::Command. It allows to easily verify the stdout and stderr (and the exit value) of programs. E.g.:
use Test::Command tests => 3;
my $echo_test = Test::Command->new( cmd => 'echo out' );
$echo_test->exit_is_num(0, 'exit normally');
$echo_test->stdout_is_eq("out\n", 'echoes out');
$echo_test->stderr_unlike( qr/something went (wrong|bad)/, 'nothing went bad' )
The module also has a functional interface too, if it's more to your liking.
A: The community standard workhorses are Test::Simple (for getting started with testing) and Test::More (for once you want more than Test::Simple can do for you). Both are built around the concept of expected versus actual output, and both will show you differences when they occur. The perldoc for these modules will get you on your way.
You might also want to check out the Perl QA wiki, and if you're really interested in perl testing, the perl-qa mailing list might be worth looking into -- though it's generally more about creation of testing systems for Perl than using those systems within the language.
Finally, using the module-starter tool (from Module::Starter) will give you a really nice "CPAN standard" layout for new work -- or for dropping existing code into -- including a readymade test harness setup.
A: Perl has excellent utilities for doing testing. The most commonly used module is probably Test::More, which provides all the infrastructure you're likely to need for writing regression tests. The prove utility provides an easy interface for running test suites and summarizing the results. The Test::Differences module (which can be used with Test::More) might be useful to you as well. It formats differences as side-by-side comparisons. As for committing the actual output as the new reference material, that will depend on how your code under test provides output and how you capture it. It should be easy if you write to files and then compare them. If that's the case you might want to use the Text::Diff module within your test suite.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What are the first tasks for implementing Unit Testing in Brownfield Applications? Do you refactor your SQL first? Your architecture? or your code base?
Do you change languages? Do you throw everything away and start from scratch? [Not refactoring]
A: I'm adding unit testing to a large, legacy spaghetti codebase.
My approach is, when asked to solve a problem, I try to create a new wrapper around the part of the code-base which is relevant to my current task. This new wrapper is developed using TTD (writing the test first). Some of the time calling into the non-unit tested legacy code. At other times I make a new copy of an existing module and start to do serious violence to it. Sometimes I rewrite functionality from scratch.
But as I'm keeping it fairly well tested I feel pretty in control.
What I find with this code-base, which has been developed with far too much copy and pasting, is that once I get an understanding a particular part, and extract some functions from it (which are done test-first) ... these functions often turn out to be usable in many other places and so the rate of replacing the legacy code with my own, unit tested libraries increases.
I don't (and have no authority to) try to rewrite or add tests to parts of the code that are not touched by my current problem (usually a bug I'm trying to fix) but I do have a fairly aggressive proactive stance on anything that is touched and might be relevant.
Update : Penguinix asked : "What languages do you work in? Is there a specific Testing Harness you recommend?"
Right now I'm working in ... er ... Mumps! But the same principle works anywhere.
Something that transformed my understanding of UT was MinUnit : http://www.jera.com/techinfo/jtns/jtn002.html
When I saw MinUnit, that was kind of a "zen" moment of enlightenment for me. It stripped away the misunderstandings I had about unit testing being something complicated requiring sophisticated OO frameworks etc. I understood that UT was just about writing a bunch of tests. The "harness" you can write yourself, in about 3 minutes, in any language you like. Just get on and do it.
A: This really depends on the state of the codebase... are there massive classes? one class with mega-methods? Are the classes tightly coupled? is configuration a burden?
Considering this, I suggest reading Working Effectively with Legacy Code, picking out your problems, and applying the recommendations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Get external IP address over remoting in C# I need to find out the external IP of the computer a C# application is running on.
In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side?
(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)
Solution:
I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
IMessage requestmessage, ITransportHeaders requestHeaders,
System.IO.Stream requestStream, out IMessage responseMessage,
out ITransportHeaders responseHeaders, out System.IO.Stream responseStream)
{
try
{
// Get the IP address and add it to the call context.
IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress];
CallContext.SetData("ClientIP", ipAddr);
}
catch (Exception)
{
}
sinkStack.Push(this, null);
ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders,
requestStream, out responseMessage, out responseHeaders, out responseStream);
return srvProc;
}
And then later (when I get a request from a client) just get the IP from the CallContext like this.
public string GetClientIP()
{
// Get the client IP from the call context.
object data = CallContext.GetData("ClientIP");
// If the data is null or not a string, then return an empty string.
if (data == null || !(data is IPAddress))
return string.Empty;
// Return the data as a string.
return ((IPAddress)data).ToString();
}
I can now send the IP back to the client.
A: Dns.GetHostEntry(Dns.GetHostName()); will return an array of IP addresses. The first one should be the external IP, the rest will be the ones behind NAT.
So:
IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
string externalIP = IPHost.AddressList[0].ToString();
EDIT:
There are reports that this does not work for some people. It does for me, but perhaps depending on your network configuration, it may not work.
A: I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
IMessage requestmessage, ITransportHeaders requestHeaders,
System.IO.Stream requestStream, out IMessage responseMessage,
out ITransportHeaders responseHeaders, out System.IO.Stream responseStream)
{
try
{
// Get the IP address and add it to the call context.
IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress];
CallContext.SetData("ClientIP", ipAddr);
}
catch (Exception)
{
}
sinkStack.Push(this, null);
ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders,
requestStream, out responseMessage, out responseHeaders, out responseStream);
return srvProc;
}
And then later (when I get a request from a client) just get the IP from the CallContext like this.
public string GetClientIP()
{
// Get the client IP from the call context.
object data = CallContext.GetData("ClientIP");
// If the data is null or not a string, then return an empty string.
if (data == null || !(data is IPAddress))
return string.Empty;
// Return the data as a string.
return ((IPAddress)data).ToString();
}
I can now send the IP back to the client.
A: Better to just use http://www.whatismyip.com/automation/n09230945.asp it only outputs the IP just for the automated lookups.If you want something that does not rely on someone else put up your own page http://www.unkwndesign.com/ip.php is just a quick script:
<?php
echo 'Your Public IP is: ' . $_SERVER['REMOTE_ADDR'];
?>
The only downside here is that it will only retrieve the external IP of the interface that was used to create the request.
A: Jonathan Holland's answer is fundamentally correct, but it's worth adding that the API calls behind Dns.GetHostByName are fairly time consuming and it's a good idea to cache the results so that the code only has to be called once.
A: The main issue is the public IP address is not necessarily correlated to the local computer running the application. It is translated from the internal network through the firewall. To truly obtain the public IP without interrogating the local network is to make a request to an internet page and return the result. If you do not want to use a publicly available WhatIsMyIP.com type site you can easily create one and host it yourself - preferably as a webservice so you can make a simple soap compliant call to it from within your application. You wouldn't necessarily do a screen capture as much as a behind the scenes post and read the response.
A: This is one of those questions where you have to look deeper and maybe rethink the original problem; in this case, "Why do you need an external IP address?"
The issue is that the computer may not have an external IP address. For example, my laptop has an internal IP address (192.168.x.y) assigned by the router. The router itself has an internal IP address, but its "external" IP address is also internal. It's only used to communicate with the DSL modem, which actually has the external, internet-facing IP address.
So the real question becomes, "How do I get the Internet-facing IP address of a device 2 hops away?" And the answer is generally, you don't; at least not without using a service such as whatismyip.com that you have already dismissed, or doing a really massive hack involving hardcoding the DSL modem password into your application and querying the DSL modem and screen-scraping the admin page (and God help you if the modem is ever replaced).
EDIT: Now to apply this towards the refactored question, "How do I get the IP address of my client from a server .NET component?" Like whatismyip.com, the best the server will be able to do is give you the IP address of your internet-facing device, which is unlikely to be the actual IP address of the computer running the application. Going back to my laptop, if my Internet-facing IP was 75.75.75.75 and the LAN IP was 192.168.0.112, the server would only be able to see the 75.75.75.75 IP address. That will get it as far as my DSL modem. If your server wanted to make a separate connection back to my laptop, I would first need to configure the DSL modem and any routers inbetween it and my laptop to recognize incoming connections from your server and route them appropriately. There's a few ways to do this, but it's outside the scope of this topic.
If you are in fact trying to make a connection out from the server back to the client, rethink your design because you are delving into WTF territory (or at least, making your application that much harder to deploy).
A: If you just want the IP that's bound to the adapter, you can use WMI and the Win32_NetworkAdapterConfiguration class.
http://msdn.microsoft.com/en-us/library/aa394217(VS.85).aspx
A: Patrik's solution works for me!
I made one important change. In process message I set the CallContext using this code:
// try to set the call context
LogicalCallContext lcc = (LogicalCallContext)requestMessage.Properties["__CallContext"];
if (lcc != null)
{
lcc.SetData("ClientIP", ipAddr);
}
This places the ip address in the correct CallContext, so it can later be retrieved with
GetClientIP().
A: Well, assuming you have a System.Net.Sockets.TcpClient connected to your client, you can (on the server) use client.Client.RemoteEndPoint. This will give you a System.Net.EndPoint pointing to the client; that should contain an instance of the System.Net.IPEndPoint subclass, though I'm not sure about the conditions for that. After casting to that, you can check it's Address property to get the client's address.
In short, we have
using (System.Net.Sockets.TcpClient client = whatever) {
System.Net.EndPoint ep = client.Client.RemoteEndPoint;
System.Net.IPEndPoint ip = (System.Net.IPEndPoint)ep;
DoSomethingWith(ip.Address);
}
Good luck.
A: I believe theoretically you are unable to do such a thing while being behind a router (e.g. using invalid ip ranges) without using an external "help".
A: The most reliable manner of doing this is checking a site like http://checkip.dyndns.org/ or similar, because until you actually go external to your network, you cannot find your external IP. However, hardcoding such a URL is asking for eventual failure. You may wish to only perform this check if the current IP looks like an RFC1918 private address (192.168.x.x being the most familiar of these.
Failing that, you can implement your own, similar, service sitting external to the firewall, so you will at least know if it's broken.
A: You can basically parse the page returned by doing a WebRequest of http://whatismyipaddress.com
http://www.dreamincode.net/forums/showtopic24692.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Is it possible to cache a value evaluated in a lambda expression? In the ContainsIngredients method in the following code, is it possible to cache the p.Ingredients value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside p eg. p.InnerObject.ExpensiveMethod().Value
edit:
I'm using the PredicateBuilder from http://www.albahari.com/nutshell/predicatebuilder.html
public class IngredientBag
{
private readonly Dictionary<string, string> _ingredients = new Dictionary<string, string>();
public void Add(string type, string name)
{
_ingredients.Add(type, name);
}
public string Get(string type)
{
return _ingredients[type];
}
public bool Contains(string type)
{
return _ingredients.ContainsKey(type);
}
}
public class Potion
{
public IngredientBag Ingredients { get; private set;}
public string Name {get; private set;}
public Potion(string name) : this(name, null)
{
}
public Potion(string name, IngredientBag ingredients)
{
Name = name;
Ingredients = ingredients;
}
public static Expression<Func<Potion, bool>>
ContainsIngredients(string ingredientType, params string[] ingredients)
{
var predicate = PredicateBuilder.False<Potion>();
// Here, I'm accessing p.Ingredients several times in one
// expression. Is there any way to cache this value and
// reference the cached value in the expression?
foreach (var ingredient in ingredients)
{
var temp = ingredient;
predicate = predicate.Or (
p => p.Ingredients != null &&
p.Ingredients.Contains(ingredientType) &&
p.Ingredients.Get(ingredientType).Contains(temp));
}
return predicate;
}
}
[STAThread]
static void Main()
{
var potions = new List<Potion>
{
new Potion("Invisibility", new IngredientBag()),
new Potion("Bonus"),
new Potion("Speed", new IngredientBag()),
new Potion("Strength", new IngredientBag()),
new Potion("Dummy Potion")
};
potions[0].Ingredients.Add("solid", "Eye of Newt");
potions[0].Ingredients.Add("liquid", "Gall of Peacock");
potions[0].Ingredients.Add("gas", "Breath of Spider");
potions[2].Ingredients.Add("solid", "Hair of Toad");
potions[2].Ingredients.Add("gas", "Peacock's anguish");
potions[3].Ingredients.Add("liquid", "Peacock Sweat");
potions[3].Ingredients.Add("gas", "Newt's aura");
var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad")
.Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion"));
foreach (var result in
from p in potions
where(predicate).Compile()(p)
select p)
{
Console.WriteLine(result.Name);
}
}
A: Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.Ingredients as a parameter...
private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)
{
return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient);
}
public static Expression<Func<Potion, bool>>
ContainsIngredients(string ingredientType, params string[] ingredients)
{
var predicate = PredicateBuilder.False<Potion>();
// Here, I'm accessing p.Ingredients several times in one
// expression. Is there any way to cache this value and
// reference the cached value in the expression?
foreach (var ingredient in ingredients)
{
var temp = ingredient;
predicate = predicate.Or(
p => IsIngredientPresent(p.Ingredients, ingredientType, temp));
}
return predicate;
}
A: Have you considered Memoization?
The basic idea is this; if you have an expensive function call, there is a function which will calculate the expensive value on first call, but return a cached version thereafter. The function looks like this;
static Func<T> Remember<T>(Func<T> GetExpensiveValue)
{
bool isCached= false;
T cachedResult = default(T);
return () =>
{
if (!isCached)
{
cachedResult = GetExpensiveValue();
isCached = true;
}
return cachedResult;
};
}
This means you can write this;
// here's something that takes ages to calculate
Func<string> MyExpensiveMethod = () =>
{
System.Threading.Thread.Sleep(5000);
return "that took ages!";
};
// and heres a function call that only calculates it the once.
Func<string> CachedMethod = Remember(() => MyExpensiveMethod());
// only the first line takes five seconds;
// the second and third calls are instant.
Console.WriteLine(CachedMethod());
Console.WriteLine(CachedMethod());
Console.WriteLine(CachedMethod());
As a general strategy, it might help.
A: Well, in this case, if you can't use Memoization, you're rather restricted since you can really only use the stack as your cache: You've got no way to declare a new variable at the scope you'll need. All I can think of (and I'm not claiming it will be pretty) that will do what you want but retain the composability you need would be something like...
private static bool TestWith<T>(T cached, Func<T, bool> predicate)
{
return predicate(cached);
}
public static Expression<Func<Potion, bool>>
ContainsIngredients(string ingredientType, params string[] ingredients)
{
var predicate = PredicateBuilder.False<Potion>();
// Here, I'm accessing p.Ingredients several times in one
// expression. Is there any way to cache this value and
// reference the cached value in the expression?
foreach (var ingredient in ingredients)
{
var temp = ingredient;
predicate = predicate.Or (
p => TestWith(p.Ingredients,
i => i != null &&
i.Contains(ingredientType) &&
i.Get(ingredientType).Contains(temp));
}
return predicate;
}
You could combine together the results from multiple TestWith calls into a more complex boolean expression where required - caching the appropriate expensive value with each call - or you can nest them within the lambdas passed as the second parameter to deal with your complex deep hierarchies.
It would be quite hard to read code though and since you might be introducing a bunch more stack transitions with all the TestWith calls, whether it improves performance would depend on just how expensive your ExpensiveCall() was.
As a note, there won't be any inlining in the original example as suggested by another answer since the expression compiler doesn't do that level of optimisation as far as I know.
A: I would say no in this case. I assume that the compiler can figure out that it uses the p.Ingredients variable 3 times and will keep the variable closeby on the stack or the registers or whatever it uses.
A: Turbulent Intellect has the exactly right answer.
I just want to advise that you can strip some of the nulls and exceptions out of the types you are using to make it friendlier to use them.
public class IngredientBag
{
private Dictionary<string, string> _ingredients =
new Dictionary<string, string>();
public void Add(string type, string name)
{
_ingredients[type] = name;
}
public string Get(string type)
{
return _ingredients.ContainsKey(type) ? _ingredients[type] : null;
}
public bool Has(string type, string name)
{
return name == null ? false : this.Get(type) == name;
}
}
public Potion(string name) : this(name, new IngredientBag()) { }
Then, if you have the query parameters in this structure...
Dictionary<string, List<string>> ingredients;
You can write the query like this.
from p in Potions
where ingredients.Any(i => i.Value.Any(v => p.IngredientBag.Has(i.Key, v))
select p;
PS, why readonly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Dynamic Database Schema What is a recommended architecture for providing storage for a dynamic logical database schema?
To clarify: Where a system is required to provide storage for a model whose schema may be extended or altered by its users once in production, what are some good technologies, database models or storage engines that will allow this?
A few possibilities to illustrate:
*
*Creating/altering database objects via dynamically generated DML
*Creating tables with large numbers of sparse physical columns and using only those required for the 'overlaid' logical schema
*Creating a 'long, narrow' table that stores dynamic column values as rows that then need to be pivoted to create a 'short, wide' rowset containing all the values for a specific entity
*Using a BigTable/SimpleDB PropertyBag type system
Any answers based on real world experience would be greatly appreciated
A: I have a similar requirement and decided to use the schema-less MongoDB.
MongoDB (from "humongous") is an open source, scalable, high-performance, schema-free, document-oriented database written in the C++ programming language. (Wikipedia)
Highlights:
*
*has rich query functionality (maybe the closest to SQL DBs)
*production ready (foursquare, sourceforge use it)
Lowdarks (stuff you need to understand, so you can use mongo correctly):
*
*no transactions (actually it has transactions but only on atomic operations)
*this stuff here: http://ethangunderson.com/blog/two-reasons-to-not-use-mongodb/
*durability .. mostly ACID related stuff
A: The whole point of having a relational DB is keeping your data safe and consistent. The moment you allow users to alter the schema, there goes your data integrity...
If your need is to store heterogeneous data, for example like a CMS scenario, I would suggest storing XML validated by an XSD in a row. Of course you lose performance and easy search capabilities, but it's a good trade off IMHO.
Since it's 2016, forget XML! Use JSON to store the non-relational data bag, with an appropriately typed column as backend. You shouldn't normally need to query by value inside the bag, which will be slow even though many contemporary SQL databases understand JSON natively.
A: I did it ones in a real project:
The database consisted of one table with one field which was an array of 50. It had a 'word' index set on it. All the data was typeless so the 'word index' worked as expected. Numeric fields were represented as characters and the actual sorting had been done at client side. (It still possible to have several array fields for each data type if needed).
The logical data schema for logical tables was held within the same database with different table row 'type' (the first array element). It also supported simple versioning in copy-on-write style using same 'type' field.
Advantages:
*
*You can rearrange and add/delete your columns dynamically, no need for dump/reload of database. Any new column data may be set to initial value (virtually) in zero time.
*Fragmentation is minimal, since all records and tables are same size, sometimes it gives better performance.
*All table schema is virtual. Any logical schema stucture is possible (even recursive, or object-oriented).
*It is good for "write-once, read-mostly, no-delete/mark-as-deleted" data (most Web apps actually are like that).
Disadvantages:
*
*Indexing only by full words, no abbreviation,
*Complex queries are possible, but with slight performance degradation.
*Depends on whether your preferred database system supports arrays and word indexes (it was inplemented in PROGRESS RDBMS).
*Relational model is only in programmer's mind (i.e. only at run-time).
And now I'm thinking the next step could be - to implement such a database on the file system level. That might be relatively easy.
A: What you are proposing is not new. Plenty of people have tried it... most have found that they chase "infinite" flexibility and instead end up with much, much less than that. It's the "roach motel" of database designs -- data goes in, but it's almost impossible to get it out. Try and conceptualize writing the code for ANY sort of constraint and you'll see what I mean.
The end result typically is a system that is MUCH more difficult to debug, maintain, and full of data consistency problems. This is not always the case, but more often than not, that is how it ends up. Mostly because the programmer(s) don't see this train wreck coming and fail to defensively code against it. Also, often ends up the case that the "infinite" flexibility really isn't that necessary; it's a very bad "smell" when the dev team gets a spec that says "Gosh I have no clue what sort of data they are going to put here, so let 'em put WHATEVER"... and the end users are just fine having pre-defined attribute types that they can use (code up a generic phone #, and let them create any # of them -- this is trivial in a nicely normalized system and maintains flexibility and integrity!)
If you have a very good development team and are intimately aware of the problems you'll have to overcome with this design, you can successfully code up a well designed, not terribly buggy system. Most of the time.
Why start out with the odds stacked so much against you, though?
Don't believe me? Google "One True Lookup Table" or "single table design". Some good results:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:10678084117056
http://thedailywtf.com/Comments/Tom_Kyte_on_The_Ultimate_Extensibility.aspx?pg=3
http://www.dbazine.com/ofinterest/oi-articles/celko22
http://thedailywtf.com/Comments/The_Inner-Platform_Effect.aspx?pg=2
A: Sounds to me like what you really want is some sort of "meta-schema", a database schema which is capable of describing a flexible schema for storing the actual data. Dynamic schema changes are touchy and not something you want to mess with, especially not if users are allowed to make the change.
You're not going to find a database which is more suited to this task than any other, so your best bet is just to select one based on other criteria. For example, what platform are you using to host the DB? What language is the app written in? etc
To clarify what I mean by "meta-schema":
CREATE TABLE data (
id INTEGER NOT NULL AUTO_INCREMENT,
key VARCHAR(255),
data TEXT,
PRIMARY KEY (id)
);
This is a very simple example, you would likely have something more specific to your needs (and hopefully a little easier to work with), but it does serve to illustrate my point. You should consider the database schema itself to be immutable at the application level; any structural changes should be reflected in the data (that-is, the instantiation of that schema).
A: I know that models indicated in the question are used in production systems all over. A rather large one is in use at a large university/teaching institution that I work for. They specifically use the long narrow table approach to map data gathered by many varied data acquisition systems.
Also, Google recently released their internal data sharing protocol, protocol buffer, as open source via their code site. A database system modeled on this approach would be quite interesting.
Check the following:
Entity-attribute-value model
Google Protocol Buffer
A: Create 2 databases
*
*DB1 contains static tables, and represents the "real" state of the data.
*DB2 is free for users to do with as they wish - they (or you) will have to write code to populate their odd-shaped tables from DB1.
A: A strongly typed xml field in MSSQL has worked for us.
A: EAV approach i believe is the best approach, but comes with a heavy cost
A: I know it's an old topic, but I guess that it never loses actuality.
I'm developing something like that right now.
Here is my approach.
I use a server setting with a MySQL, Apache, PHP, and Zend Framework 2 as application framework, but it should work as well with any other settings.
Here is a simple implementation guide, you can evolve it yourself further from this.
You would need to implement your own query language interpreter, because the effective SQL would be too complicated.
Example:
select id, password from user where email_address = "[email protected]"
The physical database layout:
Table 'specs': (should be cached in your data access layer)
*
*id: int
*parent_id: int
*name: varchar(255)
Table 'items':
*
*id: int
*parent_id: int
*spec_id: int
*data: varchar(20000)
Contents of table 'specs':
*
*1, 0, 'user'
*2, 1, 'email_address'
*3, 1, 'password'
Contents of table 'items':
*
*1, 0, 1, ''
*2, 1, 2, '[email protected]'
*3, 1, 3, 'my password'
The translation of the example in our own query language:
select id, password from user where email_address = "[email protected]"
to standard SQL would look like this:
select
parent_id, -- user id
data -- password
from
items
where
spec_id = 3 -- make sure this is a 'password' item
and
parent_id in
( -- get the 'user' item to which this 'password' item belongs
select
id
from
items
where
spec_id = 1 -- make sure this is a 'user' item
and
id in
( -- fetch all item id's with the desired 'email_address' child item
select
parent_id -- id of the parent item of the 'email_address' item
from
items
where
spec_id = 2 -- make sure this is a 'email_address' item
and
data = "[email protected]" -- with the desired data value
)
)
You will need to have the specs table cached in an associative array or hashtable or something similar to get the spec_id's from the spec names. Otherwise you would need to insert some more SQL overhead to get the spec_id's from the names, like in this snippet:
Bad example, don't use this, avoid this, cache the specs table instead!
select
parent_id,
data
from
items
where
spec_id = (select id from specs where name = "password")
and
parent_id in (
select
id
from
items
where
spec_id = (select id from specs where name = "user")
and
id in (
select
parent_id
from
items
where
spec_id = (select id from specs where name = "email_address")
and
data = "[email protected]"
)
)
I hope you get the idea and can determine for yourself whether that approach is feasible for you.
Enjoy! :-)
A: Like some others have said, don't do this unless you have no other choice. One case where this is required is if you are selling an off-the-shelf product that must allow users to record custom data. My company's product falls into this category.
If you do need to allow your customers to do this, here are a few tips:
- Create a robust administrative tool to perform the schema changes, and do not allow these changes to be made any other way.
- Make it an administrative feature; don't allow normal users to access it.
- Log every detail about every schema change. This will help you debug problems, and it will also give you CYA data if a customer does something stupid.
If you can do those things successfully (especially the first one), then any of the architectures you mentioned will work. My preference is to dynamically change the database objects, because that allows you to take advantage of your DBMS's query features when you access the data stored in the custom fields. The other three options require you load large chunks of data and then do most of your data processing in code.
A: Over at the c2.com wiki, the idea of "Dynamic Relational" was explored. You DON'T need a DBA: columns and tables are Create-On-Write, unless you start adding constraints to make it act more like a traditional RDBMS: as a project matures, you can incrementally "lock it down".
Conceptually you can think of each row as an XML statement. For example, an employee record could be represented as:
<employee lastname="Li" firstname="Joe" salary="120000" id="318"/>
This does not imply it has to be implemented as XML, it's just a handy conceptualization. If you ask for a non-existing column, such as "SELECT madeUpColumn ...", it's treated as blank or null (unless added constraints forbid such). And it's possible to use SQL, although one has to be careful about comparisons because of the implied type model. But other than type handling, users of a Dynamic Relational system would feel right at home because they can leverage most of their existing RDBMS knowledge. Now, if somebody would just build it...
A: In the past I've chosen option C -- Creating a 'long, narrow' table that stores dynamic column values as rows that then need to be pivoted to create a 'short, wide' rowset containing all the values for a specific entity.. However, I was using an ORM, and that REALLY made things painful. I can't think of how you'd do it in, say, LinqToSql. I guess I'd have to create a Hashtable to reference the fields.
@Skliwz: I'm guessing he's more interested in allowing users to create user-defined fields.
A: ElasticSearch. You should consider it especially if you're dealing with datasets that you can partition by date, you can use JSON for your data, and are not fixed on using SQL for retrieving the data.
ES infers your schema for any new JSON fields you send, either automatically, with hints, or manually which you can define/change by one HTTP command ("mappings").
Although it does not support SQL, it has some great lookup capabilities and even aggregations.
A: I know this is a super old post, and much has changed in the last 11 years, but thought I would added this as it might be helpful to future readers. One of the reason's why my co-founders and I created HarperDB is to natively accomplish Dynamic schema in a single, unduplicated data set while providing full index capability. You can read more about it here:
https://harperdb.io/blog/dynamic-schema-the-harperdb-way/
A: sql already provides a way to change your schema: the ALTER command.
simply have a table that lists the fields that users are not allowed to change, and write a nice interface for ALTER.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "69"
} |
Q: faster Math.exp() via JNI? I need to calculate Math.exp() from java very frequently, is it possible to get a native version to run faster than java's Math.exp()??
I tried just jni + C, but it's slower than just plain java.
A: Use Java's.
Also, cache results of the exp and then you can look up the answer faster than calculating them again.
A: You'd want to wrap whatever loop's calling Math.exp() in C as well. Otherwise, the overhead of marshalling between Java and C will overwhelm any performance advantage.
A: You might be able to get it to run faster if you do them in batches. Making a JNI call adds overhead, so you don't want to do it for each exp() you need to calculate. I'd try passing an array of 100 values and getting the results to see if it helps performance.
A: The real question is, has this become a bottle neck for you? Have you profiled your application and found this to be a major cause of slow down? If not, I would recommend using Java's version. Try not to pre-optimize as this will just cause development slow down. You may spend an extended amount of time on a problem that may not be a problem.
That being said, I think your test gave you your answer. If jni + C is slower, use java's version.
A: Commons Math3 ships with an optimized version: FastMath.exp(double x). It did speed up my code significantly.
Fabien ran some tests and found out that it was almost twice as fast as Math.exp():
0.75s for Math.exp sum=1.7182816693332244E7
0.40s for FastMath.exp sum=1.7182816693332244E7
Here is the javadoc:
Computes exp(x), function result is nearly rounded. It will be correctly rounded to the theoretical value for 99.9% of input values, otherwise it will have a 1 UPL error.
Method:
Lookup intVal = exp(int(x))
Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );
Compute z as the exponential of the remaining bits by a polynomial minus one
exp(x) = intVal * fracVal * (1 + z)
Accuracy: Calculation is done with 63 bits of precision, so result should be correctly rounded for 99.9% of input values, with less than 1 ULP error otherwise.
A: This has already been requested several times (see e.g. here). Here is an approximation to Math.exp(), copied from this blog posting:
public static double exp(double val) {
final long tmp = (long) (1512775 * val + (1072693248 - 60801));
return Double.longBitsToDouble(tmp << 32);
}
It is basically the same as a lookup table with 2048 entries and linear interpolation between the entries, but all this with IEEE floating point tricks. Its 5 times faster than Math.exp() on my machine, but this can vary drastically if you compile with -server.
A: +1 to writing your own exp() implementation. That is, if this is really a bottle-neck in your application. If you can deal with a little inaccuracy, there are a number of extremely efficient exponent estimation algorithms out there, some of them dating back centuries. As I understand it, Java's exp() implementation is fairly slow, even for algorithms which must return "exact" results.
Oh, and don't be afraid to write that exp() implementation in pure-Java. JNI has a lot of overhead, and the JVM is able to optimize bytecode at runtime sometimes even beyond what C/C++ is able to achieve.
A: Since the Java code will get compiled to native code with the just-in-time (JIT) compiler, there's really no reason to use JNI to call native code.
Also, you shouldn't cache the results of a method where the input parameters are floating-point real numbers. The gains obtained in time will be very much lost in amount of space used.
A: The problem with using JNI is the overhead involved in making the call to JNI. The Java virtual machine is pretty optimized these days, and calls to the built-in Math.exp() are automatically optimized to call straight through to the C exp() function, and they might even be optimized into straight x87 floating-point assembly instructions.
A: There's simply an overhead associated with using the JNI, see also:
http://java.sun.com/docs/books/performance/1st_edition/html/JPNativeCode.fm.html
So as others have suggested try to collate operations that would involve using the JNI.
A: Write your own, tailored to your needs.
For instance, if all your exponents are of the power of two, you can use bit-shifting. If you work with a limited range or set of values, you can use look-up tables. If you don't need pin-point precision, you use an imprecise, but faster, algorithm.
A: There is a cost associated with calling across the JNI boundary.
If you could move the loop that calls exp() into the native code as well, so that there is just one native call, then you might get better results, but I doubt it will be significantly faster than the pure Java solution.
I don't know the details of your application, but if you have a fairly limited set of possible arguments for the call, you could use a pre-computed look-up table to make your Java code faster.
A: There are faster algorithms for exp depending on what your'e trying to accomplish. Is the problem space restricted to a certain range, do you only need a certain resolution, precision, or accuracy, etc.
If you define your problem very well, you may find that you can use a table with interpolation, for instance, which will blow nearly any other algorithm out of the water.
What constraints can you apply to exp to gain that performance trade-off?
-Adam
A:
I run a fitting algorithm and the minimum error of the fitting result is way larger
than the precision of the Math.exp().
Transcendental functions are always much more slower than addition or multiplication and a well-known bottleneck. If you know that your values are in a narrow range, you can simply build a lookup-table (Two sorted array ; one input, one output). Use Arrays.binarySearch to find the correct index and interpolate value with the elements at [index] and [index+1].
Another method is to split the number. Lets take e.g. 3.81 and split that in 3+0.81.
Now you multiply e = 2.718 three times and get 20.08.
Now to 0.81. All values between 0 and 1 converge fast with the well-known exponential series
1+x+x^2/2+x^3/6+x^4/24.... etc.
Take as much terms as you need for precision; unfortunately it's slower if x approaches 1. Lets say you go to x^4, then you get 2.2445 instead of the correct 2.2448
Then multiply the result 2.781^3 = 20.08 with 2.781^0.81 = 2.2445 and you have the result
45.07 with an error of one part of two thousand (correct: 45.15).
A: It might not be relevant any more, but just so you know, in the newest releases of the OpenJDK (see here), Math.exp should be made an intrinsic (if you don't know what that is, check here).
This will make performance unbeatable on most architectures, because it means the Hotspot VM will replace the call to Math.exp by a processor-specific implementation of exp at runtime. You can never beat these calls, as they are optimized for the architecture...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do you launch the JavaScript debugger in Google Chrome? When using Google Chrome, I want to debug some JavaScript code. How can I do that?
A: In Chrome 8.0.552 on a Mac, you can find this under menu View/Developer/JavaScript Console ... or you can use Alt+CMD+J.
A: Here, you can find the shortcuts to access the developer tools.
https://developer.chrome.com/devtools/docs/shortcuts
A: Windows and Linux:
Ctrl + Shift + I keys to open Developer Tools
Ctrl + Shift + J to open Developer Tools and bring focus to the Console.
Ctrl + Shift + C to toggle Inspect Element mode.
Mac:
⌥ + ⌘ + I keys to open Developer Tools
⌥ + ⌘ + J to open Developer Tools and bring focus to the Console.
⌥ + ⌘ + C to toggle Inspect Element mode.
Source
Other shortcuts
A: Try adding this to your source:
debugger;
It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.
A: Windows: CTRL-SHIFT-J OR F12
Mac: ⌥-⌘-J
Also available through the wrench menu (Tools > JavaScript Console):
A: Shift + Control + I opens the Developer tool window. From bottom-left second image (that looks like the following) will open/hide the console for you:
A: To open the dedicated ‘Console’ panel, either:
*
*Use the keyboard shortcuts
*
*On Windows and Linux: Ctrl + Shift + J
*On Mac: Cmd + Option + J
*Select the Chrome Menu icon, menu -> More Tools -> JavaScript Console. Or if the Chrome Developer Tools are already open, press the ‘Console’ tab.
Please refer here
A: Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)
For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser
will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)
Thanks
A: Press the F12 function key in the Chrome browser to launch the JavaScript debugger and then click "Scripts".
Choose the JavaScript file on top and place the breakpoint to the debugger for the JavaScript code.
A: Ctrl + Shift + J opens Developer Tools.
A: For Mac users, go to Google Chrome --> menu View --> Developer --> JavaScript Console.
A: The most efficient way I have found to get to the javascript debugger is by running this:
chrome://inspect
A: F12
opens the developer panel
CTRL + SHIFT + C
Will open the hover-to-inspect tool where it highlights elements as you hover and you can click to show it in the elements tab.
CTRL + SHIFT + I
Opens the developer panel with console tab
RIGHT-CLICK > Inspect
Right click any element, and click "inspect" to select it in the Elements tab of the Developer panel.
ESC
If you right-click and inspect element or similar and end up in the "Elements" tab looking at the DOM, you can press ESC to toggle the console up and down, which can be a nice way to use both.
A: These are the tools you see
Press the F12
A: From the console in Chrome, you can do console.log(data_to_be_displayed).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "440"
} |
Q: Bluetooth Signal Strength Does anyone have any idea how to track the signal strength of a bluetooth connection perferably in C#?
I was thinking using a WMI query but couldn't track down the WMI class encapsulating the connection.
The idea is when I leave my machine with my cellphone in pocket the bluetooth signal weakens and my machine locks and I don't get goated.
A: The Link Manager Protocol (LMP) running in a Bluetooth device looks after the link setup and configuration. This is all done by two devices exchanging Protocol Data Units (PDUs).The hardware and software functionality of the RSSI is provided at the LMP level that permits you to manage the RSSI Data. It allows you to read the RSSI level and control the TX RF output power (the LMP power commands) LMP for control and to get at status information.
So what you are actually looking for is defined in the LMP when using the MS Bluetooth stack.
The MS Bluetooth Stack HCI interface already supports functions below i.e
HCI_READHCIPARAMETERS
HCI_STARTHARDWARE
HCI_STOPHARDWARE
HCI_SETCALLBACK
HCI_OPENCONNECTION
HCI_READPACKET
HCI_WRITEPACKET
HCI_CLOSECONNECTION
I suppose microsoft could have implemented a function called HCI_Read_RSSI but they didn't.
To obtain the the RSSI data you will have to use the LMP to get the info you need.
Example psuedocode to read RSSI Data
// Read HCI Parameters
#include <windows.h>
#include <windev.h>
#include <bt_buffer.h>
#include <bt_hcip.h>
#include <bt_os.h>
#include <bt_debug.h>
#include <svsutil.hxx>
#include <bt_tdbg.h>
unsigned short hci_subversion, lmp_subversion, manufacturer;
unsigned char hci_version, lmp_version, lmp_features[8];
if (BthReadLocalVersion (&hci_version, &hci_subversion, &lmp_version, &lmp_subversion, &manufacturer, lmp_features) != ERROR_SUCCESS) {
SetUnloadedState ();
return 0;
}
WCHAR szLine[MAX_PATH]
unsigned char *pf = lmp_features;
if ((*pf) & 0x02) {
wsprintf (szLine, L" RSSI");
}
This will ONLY work with the Microsoft bluetooth stack. This is C++ code also. I got this from the experts exchange post(I know) at the bottom of the page.
http://www.experts-exchange.com/Programming/Wireless_Programming/Bluetooth/Q_21267430.html
There is no specific function that does it for you.
Also there is this library that may help you, I haven't looked through the documentation completely but I've heard good things about it.
http://inthehand.com/content/32feet.aspx
Goodluck man!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I rotate an image at 12 midnight every day? I need to rotate an image at 12 midnight every day from a group of 5-10 images. How can I go about doing this with JavaScript or jQuery or even PHP?
A: At a basic level what you want to do is define an array of image names then take the number of days from a given point in time then modulo (remainder after division) by the number of images and access that index in the array and set the image, e.g. (untested code)
var images = new Array("image1.gif", "image2.jpg", "sky.jpg", "city.png");
var dateDiff = new Date() - new Date(2008,01,01);
var imageIndex = Math.Round(dateDiff/1000/60/60/24) % images.length;
document.GetElementById('imageId').setAttribute('src', images[imageIndex]);
Bear in mind that any client-side solution will be using the date and time of the client so if your definition of midnight means in your timezone then you'll need to do something similar on your server in PHP.
A: Maybe I don't understand the question.
If you just want to change the image write a batch file/cron job and have it run every day.
If you want to display a certain image on Monday, and a different one of Tuesday then do something like this:
<?php
switch(date('w'))
{
case '1':
//Monday
break;
case '2':
//Tuesday:
break;
...
}
?>
A: I'd do it on first access after midnight.
A: It doesn't even have to be in cron:
<?php
// starting date for rotation
$startDate = '2008-09-15';
// array of image filenames
$images = array('file1.jpg','file2.jpg',...);
$stamp = strtotime($startDate);
$days = (time() - $stamp) / (60*60*24);
$imageFilename = $images[$days % count($images)]
?>
<img src="<?php echo $imageFilename; ?>"/>
A: Edit: I totally misread this question as "without using javascript/PHP". So disregard this response. I'm not deleting it, just in case anyone was crazy enough to want to use this method.
Doing it without Javascript, PHP, or any other form of scripting language could be difficult. Well actually, it would just be very contrived, since it would be trivial with even the most basic JS/PHP.
Anyway, to actually answer your question, the only way I can think of doing it with vanilla HTML is to set up a shell script to run at midnight. That script would just rename your files. Do this with cron (on linux) or Windows Task Scheduler with a script kinda like this: (dodgy pseudo code follows, convert to whatever you're comfortable with).
let number_of_files = 5
rename current.jpg to number_of_files.jpg
for (x = 2 to number_of_files)
rename x.jpg to (x-1).jpg
rename 1.jpg to current.jpg
In your HTML, just do this:
<img src="path/to/current.jpg" />
And every day, current.jpg should change to something new. If you're using any sort of cache-control, make sure to change it so that it doesn't get cached for longer than a few hours.
A: If you are running a linux system you can set a Cron Job or you can use the windows task scheduler if you are on windows
A: You have two options.
*
*In JavaScript, you basically have it choose an image based on the day of the week or day of the month if you have more than 7 images. Day of the month modulo by the length of the image array should let you pick the right array element.
*You need something a bit more stateful to track what's going on... using SQL you can track when images are used and pick from the rotating list. You could also use a text file maintained by PHP to track the ordered list.
The old school way is to have a cron job rotate the image, but I'd avoid that these days.
A: That depends on how you are rotating them - sequentially, randomly, or what?
There are a number of options. You can determine which image you want in PHP, and dynamically change your <img> element to point to the correct location. This is best if you are already generating your pages dynamically.
You can always point to a single URL, which is a PHP file that determines which image to show and then performs a 302 redirect to it. This is better if you have static pages that you don't want to incur the overhead of dynamic generation for.
Don't make the image URL itself serve different images. You'll screw up your cache hit ratio for no good reason and incur unnecessary overhead on what should be a static resource.
Martin, "rotate" in this context means "change on a regular basis", not "turn around an axis".
A: It depends (TM) on what exactly you want to achieve. Just want to display a "random" image? Maybe this javascript snippet will get you started:
var date = new Date();
var day = date.getDate(); // thats the day of month, use getDays() for day of week
document.getElementById('someImage').src = '/images/foo/bar_' + (day % 10) + '.gif';
A: I assume by "rotate image" you mean "change the image in use" and not "rotational transformation about an axis" -- a simple way is to have a hash table that maps day modulo X to an image name.
$imgs = array("kitten.jpg", "puppy.gif","Bob_Dole.png");
$day_index = 365 * date("Y") + date("Z")
...
<img src="<? $imgs[$day_index % count($imgs)] ?>" />
(sorry if I got the syntax wrong, I don't really know PHP))
A: Set up a directory of images.
Select seven images and name them 0.jpg, 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg, 6.jpg,
Using mootools Javascript framework with an image tag in HTML with id "rotatingimage":
var d=new Date();
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var offset = -10; // set this to your locale's UTC offset
var desiredTime = utc + (3600000*offset);
new dd = new Date(desiredTime);
$('rotatingimage').setProperty('src', dd.getDay() + '.jpg');
A: Here's a solution which will choose a random image per day from a directory, which might be easier than some other solutions posted here, since all you have to do to get something into the rotation is upload it, rather than edit an array, or name the files in arbitrary ways.
function getImageOfTheDay() {
$myDir = "path/to/images/";
// get a unique value for the day/year.
// 15th Jan 2008 -> 10152008. 3 Feb -> 10342008, 31 Dec -> 13662008
$day = sprintf("1%03d%d", date('z'), date('Y'));
// you could of course get gifs/pngs as well.
// i'm just doing this for simplicity
$jpgs = glob($myDir . "*.jpg");
mt_srand($day);
return $jpgs[mt_rand(0, count($jpgs) - 1)];
}
The only thing is that there's a possibility of seeing the same image two days in a row, since this picks it randomly. If you wanted to get them sequentially, in alphabetical order, perhaps, then use this. (only the last two lines are changed)
function getImageOfTheDay() {
$myDir = "path/to/images/";
$day = sprintf("1%03d%d", date('z'), date('Y'));
$jpgs = glob($myDir . "*.jpg");
return $jpgs[$day % count($jpgs)];
}
A: How to rotate the images has been described in a number of ways. How to detect when to trigger the rotate depends on what you are doing (please clarify and people can provide a better answer).
Options include:
*
*Trigger the rotate on 'first access after midnight'. Assumes some sort of initiating event (eg user access)
*Use the OS scheduling capabilities to trigger the rotate (cron on *nix, at/task scheduler on Windows)
*Write code to check time & rotate
Option 3 has the risk that a poorly coded solution could be overly resource intensive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can a servlet determine if the posted data is multipart/form-data? I have a servlet that is used for many different actions, used in the Front Controller pattern. Does anyone know if it is possible to tell if the data posted back to it is enctype="multipart/form-data"? I can't read the request parameters until I decide this, so I can't dispatch the request to the proper controller.
Any ideas?
A: You can call a method to get the content type.
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html#getContentType()
According to http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2, the content type will be "multipart/form-data".
Don't forget that:
*
*request.getContentType() may return null.
*request.getContentType() may not be equal to "multipart/form-data", but may just start with it.
So, with all this in mind:
if (request.getContentType() != null &&
request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 )
{
<< code block >>
}
A: ServletFileUpload implements isMultipartContent(). Perhaps you can lift this implementation (as opposed to going through the overhead to create a ServletFileUpload) for your needs.
http://www.docjar.com/html/api/org/apache/commons/fileupload/servlet/ServletFileUpload.java.html
A: If you are going to try using the request.getContentType() method presented above, be aware that:
*
*request.getContentType() may return null.
*request.getContentType() may not be equal to "multipart/form-data", but may just start with it.
With this in mind, the check you should run is :
if (request.getContentType() != null && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
// Multipart logic here
}
A: Yes, the Content-type header in the user agent's request should include multipart/form-data as described in (at least) the HTML4 spec:
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
A: You'll have to read the request parameters in order to determine this, at least on some level. The ServletRequest class has a getContentType method that you'll want to look at.
A: To expand on awm129's answer - Apache commons' implementation corresponds to this:
if (request != null
&& request.getContentType() != null
&& request.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/")) {
...
}
You can write it a lot shorter using Apache commons' org.apache.commons.lang3.StringUtils:
if (StringUtils.startsWithIgnoreCase(request.getContentType(), "multipart/")) {
...
}
A: https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getParts()
java.util.Collection getParts()
Throws:
ServletException - if this request is not of type multipart/form-data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: j2me screen flicker when switching between canvases I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects.
For example, the game menu is a Canvas object, and the actual game is a Canvas object too.
I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.
Is there anyway to avoid this?
A: I would say, that using multiple canvases is generally bad design. On some phones it will even crash. The best way would really be using one canvas with tracking state of the application. And then in paint method you would have
protected void paint(final Graphics g) {
if(menu) {
paintMenu(g);
} else if (game) {
paintGame(g);
}
}
There are better ways to handle application state with screen objects, that would make the design cleaner, but I think you got the idea :)
/JaanusSiim
A: Do you use double buffering? If the device itself does not support double buffering you should define a off screen buffer (Image) and paint to it first and then paint the end result to the real screen. Do this for each of your canvases. Here is an example:
public class MyScreen extends Canvas {
private Image osb;
private Graphics osg;
//...
public MyScreen()
{
// if device is not double buffered
// use image as a offscreen buffer
if (!isDoubleBuffered())
{
osb = Image.createImage(screenWidth, screenHeight);
osg = osb.getGraphics();
osg.setFont(defaultFont);
}
}
protected void paint(Graphics graphics)
{
if (!isDoubleBuffered())
{
// do your painting on off screen buffer first
renderWorld(osg);
// once done paint it at image on the real screen
graphics.drawImage(osb, 0, 0, Tools.GRAPHICS_TOP_LEFT);
}
else
{
osg = graphics;
renderWorld(graphics);
}
}
}
A: A possible fix is by synchronising the switch using Display.callSerially(). The flicker is probably caused by the app attempting to draw to the screen while the switch of the Canvas is still ongoing. callSerially() is supposed to wait for the repaint to finish before attempting to call run() again.
But all this is entirely dependent on the phone since many devices do not implement callSerially(), never mind follow the implementation listed in the official documentation. The only devices I've known to work correctly with callSerially() were Siemens phones.
Another possible attempt would be to put a Thread.sleep() of something huge like 1000 ms, making sure that you've called your setCurrent() method beforehand. This way, the device might manage to make the change before the displayable attempts to draw.
The most likely problem is that it is a device issue and the guaranteed fix to the flicker is simple - use one Canvas. Probably not what you wanted to hear though. :)
A: It might be a good idea to use GameCanvas class if you are writing a game. It is much better for such purpose and when used properly it should solve your problem.
A: Hypothetically, using 1 canvas with a sate machine code for your application is a good idea. However the only device I have to test applications on (MOTO v3) crashes at resources loading time just because there's too much code/to be loaded in 1 GameCanvas ( haven't tried with Canvas ). It's as painful as it is real and atm I haven't found a solution to the problem.
If you're lucky to have a good number of devices to test on, it is worth having both approaches implemented and pretty much make versions of your game for each device.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the best OpenGL java binding? I am trying to achieve better performance for my Java SWT application, and I just found out it is possible to use OpenGL in SWT. It seems there are more than one Java binding for OpenGL. Which one do you prefer?
Note that I have never used OpenGL before, and that the application needs to work on Windows, Linux and Mac OS X.
A: JOGL
My reasons can be quoted off the previously linked site:
JOGL provides full access to the APIs in the OpenGL 2.0 specification as well as nearly all vendor extensions, and integrates with the AWT and Swing widget sets.
Also if you want to have some fun learning and poking around, Processing is an excellent way to start (Processing also uses JOGL btw...)
A: JOGL is probably the only option worth considering.
Notice that there are at least two options for integrating it into an SWT application. There's a GLCanvas that belongs to SWT and a GLCanvas that belongs to AWT.
The one in SWT is not feature complete and is not really maintained. It's much better to use the AWT GLCanvas inside a SWT_AWT container.
Some code from a recent project:
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import javax.media.opengl.*;
import javax.media.opengl.glu.*;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.events.*;
public class Main implements GLEventListener
{
public static void main(String[] args)
{
Display display = new Display();
Main main = new Main();
main.runMain(display);
display.dispose();
}
void runMain(Display display)
{
final Shell shell = new Shell(display);
shell.setText("Q*bert 3D - OpenGL Exercise");
GridLayout gridLayout = new GridLayout();
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
shell.setLayout(gridLayout);
// this allows us to set particular properties for the GLCanvas
GLCapabilities glCapabilities = new GLCapabilities();
glCapabilities.setDoubleBuffered(true);
glCapabilities.setHardwareAccelerated(true);
// instantiate the canvas
final GLCanvas canvas = new GLCanvas(glCapabilities);
// we can't use the default Composite because using the AWT bridge
// requires that it have the property of SWT.EMBEDDED
Composite composite = new Composite(shell, SWT.EMBEDDED);
GridData ld = new GridData(GridData.FILL_BOTH);
composite.setLayoutData(ld);
// set the internal layout so our canvas fills the whole control
FillLayout clayout = new FillLayout();
composite.setLayout(clayout);
// create the special frame bridge to AWT
java.awt.Frame glFrame = SWT_AWT.new_Frame(composite);
// we need the listener so we get the GL events
canvas.addGLEventListener(this);
// finally, add our canvas as a child of the frame
glFrame.add(canvas);
// show it all
shell.open();
// the event loop.
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
}
A: JOGL will give you best performance and portability. But be aware that learning JOGL, which is essentially the same as learning OpenGL, is not easy.
A: Personally, I'm not even aware of Java bindings for OpenGL other than JOGL -- I think JOGL is pretty much the standard for Java OpenGL.
It works in Windows, Linux, and OS X, but you might want to read over the official documentation for some notes about specific issues in each platform.
Keep in mind that the OpenGL paradigm is quite different from Swing/AWT or the Java 2D API; OpenGL is not a drop-in replacement for Swing.
A: I'd suggest checking out LWJGL, the LightWeight Java Game Library. It's got OpenGL bindings, but it also has OpenAL bindings and some great tutorials to get you started.
Just keep in mind that Swing/SWT and OpenGL are generally used for entirely different things. You may end up wanting to use a combination of both. Just try LWJGL out and see how well it fits with what you're doing.
A: We've had lots of luck at work using JOGL. The new 2.0 version is at http://jogamp.org/ (the last "old" version is at http://download.java.net/media/jogl/builds/archive/jsr-231-1.1.1a/).
For JOGL 2 with SWT specifically, I've got a series of tutorials starting at http://wadeawalker.wordpress.com/2010/10/09/tutorial-a-cross-platform-workbench-program-using-java-opengl-and-eclipse/ that demonstrates exactly how to make cross-platform JOGL SWT applications, complete with installable native binaries.
Or if you don't want to use Eclipse RCP, here's an even simpler example that just draws one triangle with JOGL 2 and SWT. To build it, put it in a project with swt.jar (from http://www.eclipse.org/swt/) and the latest JOGL autobuild .jar and .dll files (from http://jogamp.org/). The only problem with this simple example is that it won't be cross-platform without some extra help -- you need the ability that Eclipse RCP gives you to bundle multiple sets of platform libraries together into one project.
package name.wadewalker.onetriangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.opengl.GLCanvas;
import org.eclipse.swt.opengl.GLData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import javax.media.opengl.GL;
import javax.media.opengl.GLProfile;
import javax.media.opengl.GL2;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.glu.GLU;
public class OneTriangle {
public static void main(String [] args) {
GLProfile.initSingleton( true );
GLProfile glprofile = GLProfile.get( GLProfile.GL2 );
Display display = new Display();
Shell shell = new Shell( display );
shell.setLayout( new FillLayout() );
Composite composite = new Composite( shell, SWT.NONE );
composite.setLayout( new FillLayout() );
GLData gldata = new GLData();
gldata.doubleBuffer = true;
// need SWT.NO_BACKGROUND to prevent SWT from clearing the window
// at the wrong times (we use glClear for this instead)
final GLCanvas glcanvas = new GLCanvas( composite, SWT.NO_BACKGROUND, gldata );
glcanvas.setCurrent();
final GLContext glcontext = GLDrawableFactory.getFactory( glprofile ).createExternalGLContext();
// fix the viewport when the user resizes the window
glcanvas.addListener( SWT.Resize, new Listener() {
public void handleEvent(Event event) {
setup( glcanvas, glcontext );
}
});
// draw the triangle when the OS tells us that any part of the window needs drawing
glcanvas.addPaintListener( new PaintListener() {
public void paintControl( PaintEvent paintevent ) {
render( glcanvas, glcontext );
}
});
shell.setText( "OneTriangle" );
shell.setSize( 640, 480 );
shell.open();
while( !shell.isDisposed() ) {
if( !display.readAndDispatch() )
display.sleep();
}
glcanvas.dispose();
display.dispose();
}
private static void setup( GLCanvas glcanvas, GLContext glcontext ) {
Rectangle rectangle = glcanvas.getClientArea();
glcanvas.setCurrent();
glcontext.makeCurrent();
GL2 gl = glcontext.getGL().getGL2();
gl.glMatrixMode( GL2.GL_PROJECTION );
gl.glLoadIdentity();
// coordinate system origin at lower left with width and height same as the window
GLU glu = new GLU();
glu.gluOrtho2D( 0.0f, rectangle.width, 0.0f, rectangle.height );
gl.glMatrixMode( GL2.GL_MODELVIEW );
gl.glLoadIdentity();
gl.glViewport( 0, 0, rectangle.width, rectangle.height );
glcontext.release();
}
private static void render( GLCanvas glcanvas, GLContext glcontext ) {
Rectangle rectangle = glcanvas.getClientArea();
glcanvas.setCurrent();
glcontext.makeCurrent();
GL2 gl = glcontext.getGL().getGL2();
gl.glClear( GL.GL_COLOR_BUFFER_BIT );
// draw a triangle filling the window
gl.glLoadIdentity();
gl.glBegin( GL.GL_TRIANGLES );
gl.glColor3f( 1, 0, 0 );
gl.glVertex2f( 0, 0 );
gl.glColor3f( 0, 1, 0 );
gl.glVertex2f( rectangle.width, 0 );
gl.glColor3f( 0, 0, 1 );
gl.glVertex2f( rectangle.width / 2, rectangle.height );
gl.glEnd();
glcanvas.swapBuffers();
glcontext.release();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Is there an easy way to change the behavior of a Java/Swing control when it gets focus? For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents.
Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in the control is now 1.
With Swing, this doesn't happen. The text in the control is not selected and the carat appears at one end or another of the existing text. Continuing the above example:
With a Swing JSpinner, when you tab to the spin control, the carat is at the left. You type "1" and the value in the control is now 10.
This drives me, (and my users) up a wall, and I'd like to change it. Even more important, I'd like to change it globally so the new behavior applies to JTextField, JPasswordField, JFormattedTextField, JTextArea, JComboBox, JSpinner, and so on. The only way I have found to do this to add a FocusAdapter to each control and override the focusGained() method to Do The Right Thing[tm].
There's gotta be an easier, and less fragile way. Please?
EDIT: One additional piece of information for this particular case. The form I am working with was generated using Idea's form designer. That means I normally don't actually write the code to create the components. It is possible to tell Idea that you want to create them yourself, but that's a hassle I'd like to avoid.
Motto: All good programmers are basically lazy.
A: When I've needed this in the past, I've created subclasses of the components I wanted to add "auto-clearing" functionality too. eg:
public class AutoClearingTextField extends JTextField {
final FocusListener AUTO_CLEARING_LISTENER = new FocusListener(){
@Override
public void focusLost(FocusEvent e) {
//onFocusLost(e);
}
@Override
public void focusGained(FocusEvent e) {
selectAll();
}
};
public AutoClearingTextField(String string) {
super(string);
addListener();
}
private void addListener() {
addFocusListener(AUTO_CLEARING_LISTENER);
}
}
The biggest problem is that I haven't found a "good" way to get all the standard constructors without writing overrides. Adding them, and forcing a call to addListener is the most general approach I've found.
Another option is to watch for ContainerEvents on a top-level container with a ContainerListeer to detect the presence of new widgets, and add a corresponding focus listener based on the widgets that have been added. (eg: if the container event is caused by adding a TextField, then add a focus listener that knows how to select all the text in a TextField, and so on.) If a Container is added, then you need to recursively add the ContainerListener to that new sub-container as well.
Either way, you won't need to muck about with focus listeners in your actual UI code -- it will all be taken care of at a higher level.
A: I haven't tried this myself (only dabbled in it a while ago), but you can probably get the current focused component by using:
KeyboardFocusManager (there is a static method getCurrentKeyboardFocusManager())
an adding a PropertyChangeListener to it.
From there, you can find out if the component is a JTextComponent and select all text.
A: A separate class that attaches a FocusListener to the desired text field can be written. All the focus listener would do is call selectAll() on the text widget when it gains the focus.
public class SelectAllListener implements FocusListener {
private static INSTANCE = new SelectAllListener();
public void focusLost(FocusEvent e) { }
public void focusGained(FocusEvent e) {
if (e.getSource() instanceof JTextComponent) {
((JTextComponent)e.getSource()).selectAll();
}
};
public static void addSelectAllListener(JTextComponent tc) {
tc.addFocusListener(INSTANCE);
}
public static void removeSelectAllListener(JTextComponent tc) {
tc.removeFocusListener(INSTANCE);
}
}
By accepting a JTextComponent as an argument this behavior can be added to JTextArea, JPasswordField, and all of the other text editing components directly. This also allows the class to add select all to editable combo boxes and JSpinners, where your control over the text editor component may be more limited. Convenience methods can be added:
public static void addSelectAllListener(JSpinner spin) {
if (spin.getEditor() instanceof JTextComponent) {
addSelectAllListener((JTextComponent)spin.getEditor());
}
}
public static void addSelectAllListener(JComboBox combo) {
JComponent editor = combo.getEditor().getEditorComponent();
if (editor instanceof JTextComponent) {
addSelectAllListener((JTextComponent)editor);
}
}
Also, the remove listener methods are likely unneeded, since the listener contains no exterior references to any other instances, but they can be added to make code reviews go smoother.
A: After reading the replies so far (Thanks!) I passed the outermost JPanel to the following method:
void addTextFocusSelect(JComponent component){
if(component instanceof JTextComponent){
component.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent event) {
super.focusGained(event);
JTextComponent component = (JTextComponent)event.getComponent();
// a trick I found on JavaRanch.com
// Without this, some components don't honor selectAll
component.setText(component.getText());
component.selectAll();
}
});
}
else
{
for(Component child: component.getComponents()){
if(child instanceof JComponent){
addTextFocusSelect((JComponent) child);
}
}
}
}
It works!
A: The only way I know is to create a FocusListener and attach it to your component. If you want it this FocusListener to be global to all components in your application you might consider using Aspect Oriented Programming (AOP). With AOP is possible to code it once and apply your focus listener to all components instantiated in your app without having to copy-and-paste the component.addFocusListener(listener) code throughout your application..
Your aspect would have to intercept the creation of a JComponent (or the sub-classes you want to add this behaviour to) and add the focus listener to the newly created instance. The AOP approach is better than copy-and-pasting the FocusListener to your entire code because you keep it all in a single piece of code, and don't create a maintenance nightmare once you decide to change your global behavior like removing the listener for JSpinners.
There are many AOP frameworks out there to choose from. I like JBossAOP since it's 100% pure Java, but you might like to take a look at AspectJ.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I convert GMT to LocalTime in Win32 C? I want to convert various location/date/times in history from GMT to local time. It seems that SystemTimeToTzSpecificLocalTime is better than FileTimeToLocalFileTime. When the date/time pairs also include various locations, the conversion gets hairy. I've found a data set at ftp://ftp.iana.org/tz/releases — was ftp://elsie.nci.nih.gov/pub/ — that seems to be nicely complete through history and space, but it appears to be designed to be compiled for one time zone instead of all of them.
GetDynamicTimeZoneInformation and GetTimeZoneInformationForYear functions are only available beginning in Vista / Server 2008 and I have machines back to NT 4.0. I will probably try to use them conditionally on the newer systems.
Is there a nice C package that will solve the problem for me for Windows XP and NT 4.0?
A: SystemTimeToTzSpecificLocalTime is the right function for this, but you need a way to populate a complete database of TIMEZONE_INFO structures.
For details on how you can build a set of TIMEZONE_INFO structures out of the registry itself, see this thread on egghead cafe:
http://www.eggheadcafe.com/software/aspnet/31656478/get-current-time-in-diffe.aspx
To get things truly correct across legislative changes, you'll need GetDynamicTimeZoneInformation and GetTimeZoneInformationForYear. See http://msdn.microsoft.com/en-us/library/ms724421(VS.85).aspx.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I get Column number of the cursor in a TextBox in C#? I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does.
I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line?
(I really want the Cursor Position on that line, not 'column', per se)
A: textBox.SelectionStart -
textBox.GetFirstCharIndexFromLine(textBox.GetLineFromCharIndex(textBox.SelectionStart))
A: int line = textbox.GetLineFromCharIndex(textbox.SelectionStart);
int column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line);
A: Off the top of my head, I think you want the SelectionStart property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Unescaping angle-brackets through System.Xml.XmlWriter I'm writing a string containing some XML via System.Xml.XmlWriter. I'm stuck using WriteString(), and from the documentation:
WriteString does the following:
The characters &, <, and > are replaced with &, <, and >, respectively.
I'd like this to stop, but I can't seem to find any XmlWriterSettings properties to control this behavior. What are some workarounds? Thanks!
David
A: Try wrapping your real content between the CDATA tags:
<![CDATA[ it's my content ]]>
A: WriteString writes your content as a literal, and &, < and > are illegal in XML text, so they are escaped.
If the other end is not unescaping them, that's where the problem lies.
If you want to write unescaped XML, use WriteRaw.
A:
I'm stuck using WriteString(),
I think that's the root of your problem. Can you explain more about your reason you're stuck using WriteString? My gut is you're using the wrong method for what you want to do
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I stub data for designers when using Expression Blend and Visual Studio? We are trying out Visual Studio 2008 and Expression Blend on a new project. The goal is to clearly define the role of the developer and designer as separate, but reap the benefit of the developer being able to directly consume the XAML produced by the designer.
For the most part this has worked great, and I really like the possibilities. One difficulty we have come across though is designing against DataBindings. In many cases, the GUI does not populate rows, or other data structures unless the application is run, and a database call is made. Consequently the designer does not have access to the visual layout of the GUI.
What I would like to do, is somehow create some simple stubbed or mocked data that the designer can use to work on the design. The big goal is to have that stubbed data show up in Expression Blend, but then be applied to the real collection at runtime.
Has anyone found a solid method of doing this?
A: I would suggest reading this blog. The final method seems to work well, your test data shows up in Blend very nicely. Just keep in mind that you have to compile the DLL before it will display the data.
A: I would look into creating XML data islands which emulate the structure of the objects you will eventually bind the UI to. This way your designer can bind the root element of the page (or user control, etc.) to the top level of your fake XML data island and all the relative paths will stay the same when you swap that data island out for the real DataContext binding.
there will be some degree of refactoring to attach to the real object when you are ready, but that is why your developers should at least know enough XAML to know how to modify the bindings properly.
it looks like the commenter above me has a link to an example of this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Checking online status from an iPhone web app Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not.
In Firefox/regular WebKit, this would be:
if(navigator.onLine)
{
onlineCode()
}
A: img src="http://aonlinesite.com/a-really-little-image.png" onload="Intenet!" onerror="NoInternet!"
A: A quick test on the iPhone shows that it is available from iPhone OS 2.2.
A: That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2.1 update included a new build of safari.
https://bugs.webkit.org/show_bug.cgi?id=19105
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java VNC Libraries Are there any VNC Libraries for Java, I need to build a JSP/Servlet based VNC server, to allow user to share their desktops with helpdesk. I've seen jVNC, but i'd like to build it myself, for a University project.
In particular, I'm looking for Java Libraries that I can use inside another servlet based application. Unfortuatnely tight VNC's source is in C.
A: have you looked at the tightVNC source? It is fairly terse http://www.tightvnc.com/download.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to handle static fields that vary by implementing class I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).
*
*I define an interface ICommand
*I create an abstract base class CommandBase which implements ICommand, to contain common code.
*I create several implementation classes, each extending the base class (and by extension the interface).
Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...
For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:
public abstract static const string Name;
However (sadly) you cannot define static members in an interface.
I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.
UPDATE:
*
*I can't get the code formatting to work properly (Safari/Mac?). Apologies.
*The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).
*I forgot to mention - ideally I want to be able to query this information statically:
string name = CommandHelp.Name;
2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.
A: You may consider to use attributes instead of fields.
[Command("HELP")]
class HelpCommand : ICommand
{
}
A: As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you can do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:
public abstract class MyBaseClass
{
public abstract string Name { get; protected set; }
}
public class MyClass : MyBaseClass
{
public override string Name
{
get { return "CommandName"; }
protected set { }
}
}
(Note that the protected set prevents outside code changing the name.)
This may not be exactly what you're looking for, but it's as close as I think you can get. By definition, static fields do not vary; you simply can't have a member that is both static and overridable for a given class.
A: public interface ICommand {
String getName();
}
public class RealCommand implements ICommand {
public String getName() {
return "name";
}
}
Simple as that. Why bother having a static field?
Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like David B suggestion). What if someone extends the abstract class and forget to initiate the field?
A: [Suggested solution #1 of 3]
*
*Define an abstract property Name in the interface to force all implementing classes to implement the name property.
*(in c#) Add this property as abstract in the base class.
*In the implementations implement like this:
public string Name
{
get {return COMMAND_NAME;}
}
Where name is a constant defined in that class.
Advantages:
*
*Name itself defined as a constant.
*Interface mandates the property be created.
Disadvantages:
*
*Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?
A: just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name
A: What I usually do (in pseudo):
abstract class:
private const string nameConstant = "ABSTRACT";
public string Name
{
get {return this.GetName();}
}
protected virtual string GetName()
{
return MyAbstractClass.nameConstant;
}
----
class ChildClass : MyAbstractClass
{
private const string nameConstant = "ChildClass";
protected override string GetName()
{
return ChildClass.nameConstant;
}
}
Of course, if this is a library that other developers will use, it wouldn't hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception "Not Implemented".
A: [Suggested solution #2 of 3]
*
*Make a private member variable name.
*Define an abstract property Name in the interface.
*Implement the property in the base class like this:
public string Name
{
get {return Name;}
}
*Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:
public abstract class CommandBase(string commandName) : ICommand
{
name = commandName;
}
*Now all my implementations set the name in the constructor:
public class CommandHelp : CommandBase(COMMAND_NAME) {}
Advantages:
*
*My accessor code is centralised in the base class.
*The name is defined as a constant
Disadvantages
*
*Name is now an instance variable -
every instance of my Command classes
makes a new reference rather than
sharing a static variable.
A: My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:
interface A { abstract static NAME }
class B { NAME = "HELP" }
class C { NAME = "PRINT" }
Then how could this code know which NAME to link to:
void test(A a) {
a.NAME;
}
How I would suggest to implement this, is one of the following ways:
*
*Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.
*The base class has a constructor which takes name
*Use annotations and enforce their presence through the base class.
However, a much better solution is proabably to use enums:
public enum Command {
HELP { execute() }, PRINT { execute() };
abstract void execute();
}
This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.
A: [Suggested answer # 3 of 3]
I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:
[CammandAttribute(Name="HELP")]
Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.
A: From a design perspective, I think it is wrong to require a static implementation member... The relative deference between performance and memory usage between static and not for the example string is minimal. That aside, I understand that in implementation the object in question could have a significantly larger foot print...
The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited... Only properties and methods are available at the interface level.
The next design challenge is whether the code will be base or implementation specific. With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations. With base your valdiation will occur at run time but logic would be centralized in one place. Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.
So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing. Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization. I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time. All IDE's I work with make this very quick any easy. For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.
Circling back to the very specific nature of the question and ignoring many of the other design problems... If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem... Definately go with a method over properties, as there are way to many side effects to make go use of properties. Use a static member on the base class and use a static constructor on the implementations to set the name. Now keep in mind that you have to valdiate the name at run-time and not compile time. Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name. It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user. Or you could use reflection to get the implementation name and try to generate a name... The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...
For that matter you could always generate the name from the class name thru reflection... Though in the long term this could be a nightmare to maintain... It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns. Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.
A: What about something like this:
abstract class Command {
abstract CommandInfo getInfo();
}
class CommandInfo {
string Name;
string Description;
Foo Bar;
}
class RunCommand {
static CommandInfo Info = new CommandInfo() { Name = "Run", Foo = new Foo(42) };
override commandInfo getInfo() { return Info; }
}
Now you can access the information statically:
RunCommand.Info.Name;
And from you base class:
getInfo().Name;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Flip an Image horizontally I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say.
The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)
Below is the code: (Alternatively someone could send me to a good example)
$img = imagecreatefromgif("./unit.gif");
$size_x = imagesx($img);
$size_y = imagesy($img);
$temp = imagecreatetruecolor($size_x, $size_y);
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
$img = $temp;
}
else {
die("Unable to flip image");
}
header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
A: Shouldn't this:
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);
...be this:
imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
Note you should be calling these functions for the $temp image you have created, not the source image.
A: Final Results:
$size_x = imagesx($img);
$size_y = imagesy($img);
$temp = imagecreatetruecolor($size_x, $size_y);
imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
$img = $temp;
}
else {
die("Unable to flip image");
}
header("Content-type: image/gif");
imagegif($img);
imagedestroy($img);
A: If you can guarantee the presence of ImageMagick, you can use their mogrify -flop command. It preserves transparency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does anybody know how to correctly install ANTLR to work with .Net? Can ANTLR output C# using StringTemplate or any text I want it to like Yacc/Bison or does it only output to java? From the examples I've looked at it appears to be a very java centric tool.
A: I just started a small series of post about how exactly to install and use ANTLR for a .NET environment, as most documentation regarding this issue is a little out-of-date. See ANTLR for C#, Part 1.
A: The ANTLR IDE has option by which you can switch between Java and C# code generation.
Better, consult this article (the Specifying Code Generation section):
http://www.antlr2.org/doc/csharp-runtime.html
A: There is now a NuGet package that will do everything for you.
A: You can download the latest source code as a tar file from here. The C# runtime (binary) is also available directly, here.
Which solution are you looking for?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java EE SqlResultSetMapping Syntax I have the following Java 6 code:
Query q = em.createNativeQuery(
"select T.* " +
"from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
"where I.launchDate between :start and :end " +
"or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
"TripResults" );
q.setParameter( "start", range.getStart(), TemporalType.DATE );
q.setParameter( "end", range.getEnd(), TemporalType.DATE );
@SqlResultSetMapping( name="TripResults",
entities={
@EntityResult( entityClass=TripEntity.class ),
@EntityResult( entityClass=CommercialTripEntity.class )
}
)
I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac.
What am I doing wrong?
A: The Hibernate annotations docs (http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/) suggest that this should be a class-level annotation rather than occurring inline within your code. And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration:
@SqlResultSetMapping( name="TripResults",
entities={
@EntityResult( entityClass=TripEntity.class ),
@EntityResult( entityClass=CommercialTripEntity.class )
}
)
public class Foo {
public void bogus() {
Query q = em.createNativeQuery(
"select T.* " +
"from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
"where I.launchDate between :start and :end " +
"or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
"TripResults" );
q.setParameter( "start", range.getStart(), TemporalType.DATE );
q.setParameter( "end", range.getEnd(), TemporalType.DATE );
}
}
...obviously I have no evidence that the above code will actually work. I have only verified that it doesn't cause compile errors.
A: Your example comes straight out of the API docs which are unfortunately poorly presented.
Your annotation should be placed on some class, probably the one in which you will be creating the query to use the result set mapping. However, it actually doesn't matter where this annotation is placed. Your JPA provider will actually maintain a global list of all these mappings, so no matter where you define it, you will be able to use it anywhere.
This is a shortcoming of the annotation method (as opposed to specifying things in XML.) Many other things in the JPA (i.e. named queries) are defined this same way. It makes it seem like there's some kind of connection between the thing being defined and the class on which it is annotated, when it's not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: When does System.gc() do something? I know that garbage collection is automated in Java. But I understood that if you call System.gc() in your code that the JVM may or may not decide to perform garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the JVM decide to do (or not do) a GC when it sees System.gc()?
Are there any examples in which case it's a good idea to put this in your code?
A: If you use direct memory buffers, the JVM doesn't run the GC for you even if you are running low on direct memory.
If you call ByteBuffer.allocateDirect() and you get an OutOfMemoryError you can find this call is fine after triggering a GC manually.
A: In practice, it usually decides to do a garbage collection. The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.
I wouldn't depend on it in your code. If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme. The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.
A: Most JVMs will kick off a GC (depending on the -XX:DiableExplicitGC and -XX:+ExplicitGCInvokesConcurrent switch). But the specification is just less well defined in order to allow better implementations later on.
The spec needs clarification: Bug #6668279: (spec) System.gc() should indicate that we don't recommend use and don't guarantee behaviour
Internally the gc method is used by RMI and NIO, and they require synchronous execution, which: this is currently in discussion:
Bug #5025281: Allow System.gc() to trigger concurrent (not stop-the-world) full collections
A: Garbage Collection is good in Java, if we are executing Software coded in java in Desktop/laptop/server. You can call System.gc() or Runtime.getRuntime().gc() in Java.
Just note that none of those calls are guaranteed to do anything. They are just a suggestion for the jvm to run the Garbage Collector. It's up the the JVM whether it runs the GC or not. So, short answer: we don't know when it runs. Longer answer: JVM would run gc if it has time for that.
I believe, the same applies for Android. However, this might slow down your system.
A: You have no control over GC in java -- the VM decides. I've never run across a case where System.gc() is needed. Since a System.gc() call simply SUGGESTS that the VM do a garbage collection and it also does a FULL garbage collection (old and new generations in a multi-generational heap), then it can actually cause MORE cpu cycles to be consumed than necessary.
In some cases, it may make sense to suggest to the VM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy lifting occurs. For example, right after the initialization of a lot of temporary object during application startup (i.e., I just cached a TON of info, and I know I won't be getting much activity for a minute or so). Think of an IDE such as eclipse starting up -- it does a lot to initialize, so perhaps immediately after initialization it makes sense to do a full gc at that point.
A: The only example I can think of where it makes sense to call System.gc() is when profiling an application to search for possible memory leaks. I believe the profilers call this method just before taking a memory snapshot.
A: The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc(). This is the reason of this "may or may not decide to do a GC at that point".
Now, if you look at OpenJDK source code, which is the backbone of Oracle JVM, you will see that a call to System.gc() does start a GC cycle. If you use another JVM, such as J9, you have to check their documentation to find out the answer. For instance, Azul's JVM has a garbage collector that runs continuously, so a call to System.gc() won't do anything
Some other answer mention starting a GC in JConsole or VisualVM. Basically, these tools make a remote call to System.gc().
Usually, you don't want to start a garbage collection cycle from your code, as it messes up with the semantics of your application. Your application does some business stuff, the JVM takes care of memory management. You should keep those concerns separated (don't make your application do some memory management, focus on business).
However, there are few cases where a call to System.gc() might be understandable. Consider, for example, microbenchmarks. No-one wants to have a GC cycle to happen in the middle of a microbenchmark. So you may trigger a GC cycle between each measurement to make sure every measurement starts with an empty heap.
A: Normally, the VM would do a garbage collection automatically before throwing an OutOfMemoryException, so adding an explicit call shouldn't help except in that it perhaps moves the performance hit to an earlier moment in time.
However, I think I encountered a case where it might be relevant. I'm not sure though, as I have yet to test whether it has any effect:
When you memory-map a file, I believe the map() call throws an IOException when a large enough block of memory is not available. A garbage collection just before the map() file might help prevent that, I think. What do you think?
A: we can never force garbage collection. System.gc is only suggesting vm for garbage collection, however, really what time the mechanism runs, nobody knows, this is as stated by JSR specifications.
A: There is a LOT to be said in taking the time to test out the various garbage collection settings, but as was mentioned above it usually not useful to do so.
I am currently working on a project involving a memory-limited environment and a relatively large amounts of data--there are a few large pieces of data that push my environment to its limit, and even though I was able to bring memory usage down so that in theory it should work just fine, I would still get heap space errors---the verbose GC options showed me that it was trying to garbage collect, but to no avail. In the debugger, I could perform System.gc() and sure enough there would be "plenty" of memory available...not a lot of extra, but enough.
Consequently, The only time my application calls System.gc() is when it is about to enter the segment of code where large buffers necessary for processing the data will be allocated, and a test on the free memory available indicates that I'm not guaranteed to have it. In particular, I'm looking at a 1gb environment where at least 300mb is occupied by static data, with the bulk of the non-static data being execution-related except when the data being processed happens to be at least 100-200 MB at the source. It's all part of an automatic data conversion process, so the data all exists for relatively short periods of time in the long run.
Unfortunately, while information about the various options for tuning the garbage collector is available, it seems largely an experimental process and the lower level specifics needed to understand how to handle these specific situations are not easily obtained.
All of that being said, even though I am using System.gc(), I still continued to tune using command line parameters and managed to improve the overall processing time of my application by a relatively significant amount, despite being unable to get over the stumbling block posed by working with the larger blocks of data. That being said, System.gc() is a tool....a very unreliable tool, and if you are not careful with how you use it, you will wish that it didn't work more often than not.
A: If you want to know if your System.gc() is called, you can with the new Java 7 update 4 get notification when the JVM performs Garbage Collection.
I am not 100% sure that the GarbageCollectorMXBean class was introduces in Java 7 update 4 though, because I couldn't find it in the release notes, but I found the information in the javaperformancetuning.com site
A: You need to be very careful if you call System.gc(). Calling it can add unnecessary performance issues to your application, and it is not guaranteed to actually perform a collection. It is actually possible to disable explicit System.gc() via the java argument -XX:+DisableExplicitGC.
I'd highly recommend reading through the documents available at Java HotSpot Garbage Collection for more in depth details about garbage collection.
A: System.gc() is implemented by the VM, and what it does is implementation specific. The implementer could simply return and do nothing, for instance.
As for when to issue a manual collect, the only time when you may want to do this is when you abandon a large collection containing loads of smaller collections--a
Map<String,<LinkedList>> for instance--and you want to try and take the perf hit then and there, but for the most part, you shouldn't worry about it. The GC knows better than you--sadly--most of the time.
A: I can't think of a specific example when it is good to run explicit GC.
In general, running explicit GC can actually cause more harm than good, because an explicit gc will trigger a full collection, which takes significantly longer as it goes through every object. If this explicit gc ends up being called repeatedly it could easily lead to a slow application as a lot of time is spent running full GCs.
Alternatively if going over the heap with a heap analyzer and you suspect a library component to be calling explicit GC's you can turn it off adding: gc=-XX:+DisableExplicitGC to the JVM parameters.
A: Accroding to Thinking in Java by Bruce Eckel, one use case for explicit System.gc() call is when you want to force finalization, i.e. the call to finalize method.
A: while system.gc works,it will stop the world:all respones are stopped so garbage collector can scan every object to check if it is needed deleted. if the application is a web project, all request are stopped until gc finishes,and this will cause your web project can not work in a monent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "129"
} |
Q: How do I run Oracle plsql procedure from Lisp? How do I get started?
A: I have found the easiest way to achieve this by using Clojure.
Here is the example code:
(ns example
(:require [clojure.contrib.sql :as sql])
(:import [java.sql Types]))
(def devdb {:classname "oracle.jdbc.driver.OracleDriver"
:subprotocol "oracle"
:subname "thin:username/password@localhost:1509:devdb"
:create true})
(defn exec-ora-stored-proc [input-param db callback]
(sql/with-connection db
(with-open [stmt (.prepareCall (sql/connection) "{call some_schema.some_package.test_proc(?, ?, ?)}")]
(doto stmt
(.setInt 1 input-param)
(.registerOutParameter 2 Types/INTEGER)
(.registerOutParameter 3 oracle.jdbc.driver.OracleTypes/CURSOR)
(.execute))
(callback (. stmt getInt 2) (. stmt getObject 3)))))
(exec-ora-stored-proc
123 ;;input param value
devdb
(fn [err-code res-cursor]
(println (str "ret_code: " err-code))
;; prints returned refcursor rows
(let [resultset (resultset-seq res-cursor)]
(doseq [rec resultset]
(println rec)))))
A: You'll need an interface to the Oracle SQL database. As Bob pointed out, Allegro CL has such an interface.
GNU CLISP apparently comes with an interface to the database as well.
A: The most straightforward way to do Oracle stuff from your Common Lisp program is to use CLSQL. There are plenty of other packages for doing stuff with databases from Common Lisp. Have a look at Cliki's database page
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: what is the easiest way to lookup function names of a c binary in a cross-platform manner? I want to write a small utility to call arbitrary functions from a C shared library. User should be able to list all the exported functions similar to what objdump or nm does. I checked these utilities' source but they are intimidating. Couldn't find enough information on google, if dl library has this functionality either.
(Clarification edit: I don't want to just call a function which is known beforehand. I will appreciate an example fragment along your answer.)
A: This might be near to what you're looking for:
http://python.net/crew/theller/ctypes/
A: Well, I'll speak a little bit about Windows. The C functions exported from DLLs do not contain information about the types, names, or number of arguments -- nor do I believe you can determine what the calling convention is for a given function.
For comparison, take a look at National Instrument's LabVIEW programming environment. You can import functions from DLLs, but you have to manually type in the type and names of the arguments before you use a given function. If this limitation is OK, please edit your question to reflect that.
I don't know what is possible with *nix environments.
EDIT: Regarding your clarification. If you don't know what the function is ahead of time, you're pretty screwed on Windows because in general you won't be able to determine what the number and types of arguments the functions take.
A: You could try ParaDyn's SymtabAPI. It lets you grab all the symbols in a shared library (or executable) and look at their types, offset, etc. It's all wrapped up in a reasonably nice C++ interface and runs on a lot of platforms. It also provides support for binary rewriting, which you could potentially use to do what you're talking about at runtime.
Webpage is here:
http://www.paradyn.org/html/symtab2.1-features.html
Documentation is here:
http://ftp.cs.wisc.edu/paradyn/releases/release5.2/doc/symtabProgGuide.21.pdf
A: A standard-ish API is the dlopen/dlsym API; AFAIK it's implemented by GNU libc on Linux and Mac OS X's standard C library (libSystem), and it might be implemented on Windows by MinGW or other compatibility packages.
A: Only sensible solution (without reinventing the wheel) seems to use libbfd. Downsides are its documentation is scarce and it is a bit bloated for my purposes.
A: The source code for nm and objdump are available. If you want to start from specification then ELF is what you want to look into.
/Allan
A: I've written something like this in Perl. On Win32 it runs dumpbin /exports, on POSIX it runs nm -gP. Then, since it's Perl, the results are interpreted using regular expressions: / _(\S+)@\d+/ for Win32 (stdcall functions) and /^(\S+) T/ for POSIX.
A: Eek! You've touched on one of the very platform-dependent topics of programming. On windows, you have DLLs, on linux, you have ld.so, ld-linux.so, and mac os x's dyld.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Installation of demo project - best practices Using Windows Installer (targeting XP and Vista), is there a best practice for installing demo projects and files with your application?
A: From experience installing on Vista/XP I would recommend...
1, Install the source code/project/solution files into the 'Users' directory for Vista. That way when the user opens up the demo and compiles they have write access for generating the output files. If you put the files into the 'Program Files' directory under Vista you do not have write access and so the compile will just fail.
2, Add a shortcut to the solution to either the desktop or the start menu so that the user can then get access to it without having to know the exact location. Under Vista/XP when you install into the 'Users'/'Documents and Settings' directory it is not easy to find the installed files because they are placed inside a directory that is not shown unless you select 'Show Hidden Files' in file explorer.
3, I would recommend you sign the installer using your publisher certificate so that when the user gets a UAC dialog on Vista they can see the name of the publiser and be more likely to continue with the process.
4, At the moment the split between Visual Studio 2005/2008 is about 50%/50% and so make sure you provide both versions of the project/solutions files. Alternatively just supply the VS2005 files and let the user upgrade using the wizard in VS2008.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What package includes AB the Apache Server Benchmarking Tool in Ubuntu I'm trying to find ab - Apache HTTP server benchmarking tool for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.
A: % sudo apt-get install apache2-utils
The command-not-found package in Ubuntu provides some slick functionality where if you type a command that can't be resolved to an executable (or bash function or whatever) it will query your apt sources and find a package that contains the binary you tried to execute. So, in this case, I typed ab at the command prompt:
% ab
The program 'ab' is currently not installed. You can install it by typing:
sudo apt-get install apache2-utils
bash: ab: command not found
A: Another way to search for missing files, e.g. if you use zsh, want to disable command-not-found (slows things down when you misstype commandnames), or are looking for a file that is not an executable:
$ sudo aptitude install apt-file
$ sudo apt-file update
$ apt-file search bin/ab
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "86"
} |
Q: How can I create a site in php and have it generate a static version? For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client?
Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: http://gnuwin32.sourceforge.net/packages/wget.htm.
A: If you have a Linux system available to you use wget:
wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/
Options
*
*-k : convert links to relative
*-K : keep an original versions of files without the conversions made by wget
*-E : rename html files to .html (if they don’t already have an htm(l) extension)
*-r : recursive… of course we want to make a recursive copy
*-l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough.
*-p : download all necessary files for each page (css, js, images)
*-N : Turn on time-stamping.
*-F : When input is read from a file, force it to be treated as an HTML file.
*-nH : By default, wget put files in a directory named after the site’s hostname. This will disabled creating of those hostname directories and put everything in the current directory.
Source: Jean-Pascal Houde's weblog
A: build your site, then use a mirroring tool like wget or lwp-mirror to grab a static copy
A: I have done this in the past by adding:
ob_start();
In the top of the pages and then in the footer:
$page_html = ob_get_contents();
ob_end_clean();
file_put_contents($path_where_to_save_files . $_SERVER['PHP_SELF'], $page_html);
You might want to convert .php extensions to .html before baking the HTML into the files.
If you need to generate multiple pages with variables one quite easy option is to append the filename with md5sum of all GET variables, you just need to change them in the HTML too. So you can convert:
somepage.php?var1=hello&var2=hullo
to
somepage_e7537aacdbba8ad3ff309b3de1da69e1.html
ugly but works.
Sometimes you can use PHP to generate javascript to emulate some features, but that cannot be automated very easily.
A: Create the site as normal, then use spidering software to generate a HTML copy.
HTTrack is software I have used before.
A: One way to do this is to create the site in PHP as normal, and have a script actually grab the webpages (through HTTP - you can use wget or write another php script that just uses file() with URLs) and save them to the public website locations when you are "done". Then you can just run the script again when you decide to change the pages again. This method is quite useful when you have a slowly changing database and lots of traffic, as you can eliminate all SQL queries on the live site.
A: If you use modx it has a built in function to export static files.
A: If you have a number of pages, with all sorts of request variables and whatnot, probably one of the spidering tools the other commenters have mentioned (wget, lwp-mirror, etc) would be the easiest and most robust solution.
However, if the number of pages you need to get is low, or at least manageable, you've got a few options which don't require any third party tools (not that you should discount them JUSt because they are third party).
*
*You can use php on the command line to get it to output directly into a file.
php myFile.php > myFile.html
Using this method could get painful (though you could put it all into a shell script), and it doesn't allow you to pass variables in the same way (eg: php myFile.php?abc=1 won't work).
*You could use another PHP file as a "build" script which contains a list of all the URLs you want and then grabs them via file_get_contents() or file() and writes them to a local file. Using this method, you can also get it to check if the file has changed (md5_file() should work for that), so you'll know what to give your client, should they only want updates.
*Further to #2, before you write the output to file, scan it for local urls and then add those to your list of files to download. While you're there, change those urls to link to what you'll eventually name your output so you have a functioning web at the end. Note of caution here - if this is sounding good, you could probably use one of the tools which already exist and do this for you.
A: Alternatively to wget you could use (Win|Web)HTTrack (Website) to grab the static page. HTTrack even corrects links to files and documents to match the static output.
A: You can use python or visual basic (or your choice) to create your static files all at once then upload them.
For a project with 11 million business listings in excel files I used VBA to extract the spreadsheet data into 11 mil small .php files, then zipped, ftp'd, unzipped.
https://contactlookup.us
Voila - a super fast business directory
I started with Jekyll, but after about half million entries the generator got bogged down. For 11 million it looked like it would finalize the build in about 2 months!
A: I do it on my own web site for certain pages that are guaranteed not to change -- I simply run a shell script that could be boiled to (warning: bash pseudocode):
find site_folder -name \*.static.php -print -exec Staticize {} \;
with Staticize being:
# This replaces .static.php with .html
TARGET_NAME="`dirname "$1"`/"`basename "$1" .static.php`".html
php "$1" > "$TARGET_NAME"
A: wget is probably the most complete method. If you don't have access to that, and you have a template based layout, you may want to look into using Savant 3. I recommend Savant 3 highly over other template systems like Smarty.
Savant is very light weight and uses PHP as the template language, not some proprietary sublanguage. The command you would want to look up is fetch(), which will "compile" your template and place it in a variable that you can output.
http://www.phpsavant.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Threadsafe foreach enumeration of lists I need to enumerate though generic IList<> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumeration with a "Collection was modified; enumeration operation may not execute."
What is a good way of doing threadsafe foreach on a IList<>? prefferably without cloning the entire list. It is not possible to clone the actual objects referenced by the list.
A: There is no such operation. The best you can do is
lock(collection){
foreach (object o in collection){
...
}
}
A: Your problem is that an enumeration does not allow the IList to change. This means you have to avoid this while going through the list.
A few possibilities come to mind:
*
*Clone the list. Now each enumerator has its own copy to work on.
*Serialize the access to the list. Use a lock to make sure no other thread can modify it while it is being enumerated.
Alternatively, you could write your own implementation of IList and IEnumerator that allows the kind of parallel access you need. However, I'm afraid this won't be simple.
A: ICollection MyCollection;
// Instantiate and populate the collection
lock(MyCollection.SyncRoot) {
// Some operation on the collection, which is now thread safe.
}
From MSDN
A: You'll find that's a very interesting topic.
The best approach relies on the ReadWriteResourceLock which use to have big performance issues due to the so called Convoy Problem.
The best article I've found treating the subject is this one by Jeffrey Richter which exposes its own method for a high performance solution.
A: So the requirements are: you need to enumerate through an IList<> without making a copy while simultaniously adding and removing elements.
Could you clarify a few things? Are insertions and deletions happening only at the beginning or end of the list?
If modifications can occur at any point in the list, how should the enumeration behave when elements are removed or added near or on the location of the enumeration's current element?
This is certainly doable by creating a custom IEnumerable object with perhaps an integer index, but only if you can control all access to your IList<> object (for locking and maintaining the state of your enumeration). But multithreaded programming is a tricky business under the best of circumstances, and this is a complex probablem.
A: Cloning the list is the easiest and best way, because it ensures your list won't change out from under you. If the list is simply too large to clone, consider putting a lock around it that must be taken before reading/writing to it.
A: Forech depends on the fact that the collection will not change. If you want to iterate over a collection that can change, use the normal for construct and be prepared to nondeterministic behavior. Locking might be a better idea, depending on what you're doing.
A: Default behavior for a simple indexed data structure like a linked list, b-tree, or hash table is to enumerate in order from the first to the last. It would not cause a problem to insert an element in the data structure after the iterator had already past that point or to insert one that the iterator would enumerate once it had arrived, and such an event could be detected by the application and handled if the application required it. To detect a change in the collection and throw an error during enumeration I could only imagine was someone's (bad) idea of doing what they thought the programmer would want. Indeed, Microsoft has fixed their collections to work correctly. They have called their shiny new unbroken collections ConcurrentCollections (System.Collections.Concurrent) in .NET 4.0.
A: I recently spend some time multip-threading a large application and had a lot of issues with the foreach operating on list of objects shared across threads.
In many cases you can use the good old for-loop and immediately assign the object to a copy to use inside the loop. Just keep in mind that all threads writing to the objects of your list should write to different data of the objects. Otherwise, use a lock or a copy as the other contributors suggest.
Example:
foreach(var p in Points)
{
// work with p...
}
Can be replaced by:
for(int i = 0; i < Points.Count; i ++)
{
Point p = Points[i];
// work with p...
}
A: Wrap the list in a locking object for reading and writing. You can even iterate with multiple readers at once if you have a suitable lock, that allows multiple concurrent readers but also a single writer (when there are no readers).
A: This is something that I've recently had to deal with and to me it really depends on what you're doing with the list.
If you need to use the list at a point in time (given the number of elements currently in it) AND another thread can only ADD to the end of the list, then maybe you just switch out to a FOR loop with a counter. At the point you grab the counter, you're only seeing X numbers of elements in the list. You can walk through the list (while others are adding to the end of it) . . . should not cause a problem.
Now, if the list needs to have items taken OUT of it by other threads, or CLEARED by other threads, then you'll need to implement one of the locking mechanisms mentioned above. Also, you may want to look at some of the newer "concurrent" collection classes (though I don't believe they implement IList - so you may need refactor for a dictionary).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: subversion tags and branches Has anybody come up with a better technique for managing tags and branches in subversion than what is generally recommended (the parallel directories called 'tags' and 'branches')?
A: Using the repository namespace to convey information like branches / tags / etc is fundamentally the SVN model; if what you want is a different model, you probably really want something other than SVN.
The lack of metadata like CVS-style labels in SVN is an intentional design decision. No matter what arrangement of branches/tags/projects you choose in your tree, it's all going to reduce to sets of parallel directories for each purpose. What's left is just choosing the right naming strategy for your branches and tags to make things more clear to you.
One convention that I'm fond of is a separation between full heavyweight branches and lightweight "twigs". The convention in the group where I work is that long-lived development goes in a branch, and the release engineers must know of and be partially responsible for each branch, but that any engineer can create a short-lived twig to use as scratch space for a problem that's too large to fit into one checkin but not massive enough to require release engineering support. Twigs here live in a separate parallel 'twigs' directory similar to branches, and the naming convention often has the creator's user ID and the bug ID number for the issue the twig is intended to address in it.
A: We use a "trunk, tag, branch and stream" strategy.
The "trunk" is where the most current version of whatever is out in production is supposed to be placed.
A "tag" is where a "copy to" occurs when a stream is complete and we need to store the status of the stream for archival purposes. It also allows development to continue from a specific point.
A "branch" is when something completely different than mainstream development is to take place. Usually, branches are very rare.
"Streams" are what we most use. A stream of development is a task-based focus, such as a stream for a particular fix or development effort (for instance, a change requests' completion). Streams are allowed to merge with each other, but different streams are ranked based on svn strategy. For instance, we had one stream for a cr release, and another stream for pushing out app support releases. Since the CR stream had to incorporate the app support fixes in addition to its own changes, it was ranked higher. Streams that are higher ranked have lower streams (as needed) merged into them. Finally, a stream becomes production-ready. It is tagged, and then "copied to" trunk, which is then used (normally, although sometimes tags are used) as the base for further streams.
The best use of streams, however, are for short tasks that take less than two weeks to complete. These streams can be merged quickly into multiple, higher ranked streams, which then get merged later into any other higher ranked streams. For example, since app support was lower than cr, any app support quick fix could be copied to a stream and then worked on, merged to app support which would then be merged to the cr stream.
A: The only other thing you can do besides having parallel directories when you have Branches is to do an SVN Switch between two branches whenever you want to work on one or the other. Perhaps you should clarify what you want to be "better" about this system and people could make suggestions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Namespaces in C# I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces.
Example:
Project = Tully.Saps.Data
Folder = DataAccess/Interfaces
Namespace = Tully.Saps.Data.DataAccess.Interfaces
Folder = DataAccess/MbNetRepositories
Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories
Question:
Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
A: Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
A: It is really up to you how you want to deal with it. If you are only going to be accessing a member of a namespace once or twice, then adding the "using" statement really doesn't do much for you.
If you are going to use it multiple times then reducing the namespace chain is probably going to make things easier to read.
You could always change the namespace so it doesn't add the new folder name if you are just looking to logically group files together, without creating a new namespace.
A: According to FXCop, and I agree:
Avoid namespaces with few types
A namespace should generally have more than five types.
also (and this applies to the "single namespace" suggestion -- which is almost the same to say as no namespace)
Declare types in namespaces
A type should be defined inside a namespace to avoid duplication.
A: *
*Namespaces
.Namespaces help us to define the "scope" of a set of entities in our object model or our application. This makes them a software design decision not a folder structure decision. For example, in an MVC application it would make good sense to have Model/View/Controller folders and related namespaces. So, while it is possible, in some cases, that the folder structure will match the namespace pattern we decide to use in our development, it is not required and may not be what we desire. Each namespace should be a case-by-case decision
*
*using statements
To define using statements for a namespace is a seperate decision based on how often the object in that namespace will be referred to in code and should not in any way affect our namespace creation practice.
A: Leave it. It's one great example of how your IDE is dictating your coding style.
A: Just because the tool (Visual Studio) you are using has decided that each folder needs a new Namespace doesn't mean you do.
I personally tend to leave my "Data" projects as a single Namespace. If I have a subfolder called "Model" I don't want those files in the Something.Data.Model Namespace, I want them in Something.Data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Decorating a parent class method I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but not in the parent class.
Essentially, I am trying to accomplish the following:
class foo(Object):
def meth1(self, val):
self.value = val
class bar(foo):
meth1 = classmethod(foo.meth1)
A: I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with:
def convert_to_classmethod(method):
return classmethod(method.im_func)
class bar(foo):
meth1 = convert_to_classmethod(foo.meth1)
The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what "self" means.
I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.
A: What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the original programmer.
A: The question, as posed, seems quite odd to me: I can't see why anyone would want to do that. It is possible that you are misunderstanding just what a "classmethod" is in Python (it's a bit different from, say, a static method in Java).
A normal method is more-or-less just a function which takes as its first argument (usually called "self"), an instance of the class, and which is invoked as ".".
A classmethod is more-or-less just a function which takes as its first argument (often called "cls"), a class, and which can be invoked as "." OR as ".".
With this in mind, and your code shown above, what would you expect to have happen if someone creates an instance of bar and calls meth1 on it?
bar1 = bar()
bar1.meth1("xyz")
When the code to meth1 is called, it is passed two arguments 'self' and 'val'. I guess that you expect "xyz" to be passed for 'val', but what are you thinking gets passed for 'self'? Should it be the bar1 instance (in this case, no override was needed)? Or should it be the class bar (what then would this code DO)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fail fast finally clause in Java Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?
See the example below:
try {
// code that may or may not throw an exception
} finally {
SomeCleanupFunctionThatThrows();
// if currently executing an exception, exit the program,
// otherwise just let the exception thrown by the function
// above propagate
}
or is ignoring one of the exceptions the only thing you can do?
In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
A: Set a flag variable, then check for it in the finally clause, like so:
boolean exceptionThrown = true;
try {
mightThrowAnException();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
// Whatever you want to do
}
}
A: If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks:
try {
doSomethingDangerous(); // can throw exception
onSuccess();
} catch (Exception ex) {
onFailure();
}
A: If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:
try {
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) { //or catch whatever you want here
// exception handling code, or just ignore it
}
}
A: Do you mean you want the finally block to act differently depending on whether the try block completed successfully?
If so, you could always do something like:
boolean exceptionThrown = false;
try {
// ...
} catch(Throwable t) {
exceptionThrown = true;
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) {
if(exceptionThrown) ...
}
}
That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.
A: No I do not believe so. The catch block will run to completion before the finally block.
try {
// code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Google Maps style scrolling anyone? I am looking for some JavaScript plugin (preferably jQuery) to be able to scroll through an image, in the same way that Google Maps works.
I can make the image draggable but then I see the whole image while dragging even if the parent div is overflow:hidden.
Any help would be greatly appreciated!
A: Check out the Google Maps Image Cutter It can take any image or digital photo and cut it into tiles which are displayed on a Google Map. Might be a quick way to do what you need...
A: I may be a little late to the party, but I was just looking for the same thing. What I stumbled upon is scrollview for jquery, it works perfect and does exactly this google maps-like drag-to-scroll for overflowed divs.
A: You could use the google maps api...they allow for you to use it with custom images. And you can choose if the controls show up or not.
EDIT: Found a decent tutorial on how to do this.
http://mapki.com/wiki/Add_Your_Own_Custom_Map
A: For a good description of the underlying technology have a look at Chapter 4 (if I recall correctly) of the Pragmatic Programmers' book Pragmatic Ajax.
You'll see how the image slicing and dicing works under the covers. And the zooming.
A: (I'm super late to this now dead party, but hey, I found this page via a search so...)
Scrollview plugin suggested by mooware didn't work for me.
However Dragscrollable did:
http://plugins.jquery.com/project/Dragscrollable
Try out the demonstration
A: This has less to do with javascript and more to do with the CSS coding.
Try a few experiments with just HTML and CSS to get the image to clip properly, then add the javascript to move it around.
If you can't get it to clip with HTML, or move with the javascript post the simplest demonstration of the problem here for us to debug.
Without the code we're shooting in the dark.
A: Google Maps uses images sliced into blocks which are dynamically loaded as the user pans in different directions. The Google Maps Image Cutter Paul Dixon mentions is the tool you want for this.
If you just want to pan one large image, rather than have the additional complexity of slicing the image up into blocks, then instead of using the CSS overflow property, you should use the clip property. This is supported on all browsers worth thinking about, down to IE4 if I remember correctly.
One point to note: the CSS2.1 spec shows examples with the rect values separated by commas. However this isn't supported by IE6 (perhaps not IE7, either). However all other browsers understand the version without commas. So instead of
clip: rect(5px, 40px, 45px, 5px);
you should use
clip: rect(5px 40px 45px 5px);
for compatibility.
You need a container <div> set to position:relative around the <img> element, which you then set to position: absolute.
So the basic technique is to update the top and left values as the user drags, use these together with the defined width and height of the view onto the image to create the appropriate rect() string, and update the top, left, and clip properties of the <img> element's style property.
Don't do what I did and leave out the "px" after the values in the rect() string. It took me ages to realise why it wasn't working :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Setting movie metadata with QTKit I'm trying to convert old QuickTime framework code to the 64-bit Cocoa-based QTKit on OS X, which means that I can't drop down to the straight C function calls at any time. Specifically, I'm trying to find a way to write QuickTime VR movies with QTKit, as they require some special metadata to set the display controller. How can I do this with QTKit?
A: If you have to delve down into the C APIs, you might tackle the limitation to 32-bit builds by moving the QuickTime specific code into a separate, 32-bit process. We do this on Windows and it works quite well ...
A: As far as I can tell from the QTKit Documentation there is not way to do this in straight QTKit cocoa calls. You'll need to do this using the Quicktime-C APIs, which of course aren't available to 64-bit applications.
I've run into issues like this numerous times when trying to convert a 32-bit app that uses Quicktime into a 64-bit app. Here's hoping that Quicktime X will have a more fully featured QTKit set of APIs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem with unicode String literal in unit test I have a JUnit test that tests adding Strings to a Dictionary custom type. Everything works fine for everyone else on a Linux/Windows machine, however, being the first dev in my shop on a mac, this unit test fails for me. The offending lines are where unicode string literals are used:
dict.add( "Su字/会意pin", "Su字/会意pin" );
dict.add( "字/会意", "字/会意" );
Is there a platform-independent way to specify the unicode string? I've tried changing the encoding of the file in Eclipse to UTF-8 instead of the default MacRoman, but the test still fails.
A: In the flags for the javac compiler, set the -encoding flag, so in your case you'd mark it as
javac -encoding UTF-8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Any recommendations for deployment from SVN, with version numbers written into my code automagically? I've gotten comfy with SVN, and now I need a way to deploy my code to staging or live servers more easily. I'd also like some method for putting build info in the footer of this site to aid in testing. Site is PHP/MySQL.
A: First enable keyword substitution for a file where you wish to have the revision info:
svn propset svn:keywords "Rev" file.txt
The add to the file where you want the Revision info stored:
$Rev$
Further readings: http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html
A: The properties methods will only give you the last revision number of the file you have the property in, not the head revision of the whole repository (a la the Stack Overflow footer). If you are wanting that, you'll need to use svnversion.
I recently started using Capistrano on a project and it superb and very flexible and powerful. I ended up deviating quite far from its normal usage, but it makes one "click" deployment much easier.
A: A script to svn update on an as needed basis.
SVN supports keywords. You can add which keywords you want to expand to the keywords property, and SVN will expand then. See $Id$ or $Rev$, or keywords described in the SVN book.
A: If you want to update the version number in a projects AssemblyInfo.cs you may be interested in this article:
CodeProject: Use Subversion Revision numbers in your Visual Studio Projects
If you enable SVN Keywords then every time you check in the project Subversion scans your files for certain "keywords" and replaces the keywords with some information.
For example, At the top of my source files I would create a header contain the following keywords:
'$Author:$
'$Id:$
'$Rev:$
When I check this file into Subversion these keywords are replaced with the following:
'$Author: paulbetteridge $
'$Id: myfile.vb 145 2008-07-16 15:24:29Z paulbetteridge $
'$Rev: 145 $
A: I'm a fan of using capistrano for pushes. Refer to here.
You could use the SVN $Rev$ property to get the revision number into your footer.
A: A really simple way to manage this is to setup your app in the following way:
Simply make your deployment app a working copy of your trunk (svn co the project to your /www root) and you run an svn up through an ssh console (ssh [email protected] svn up /path/to/project) when you need to update. You can also rollback with the appropriate checkout mechanisms. This is important: if you do this, add RewriteRules (or equivalent) to your .htaccess (or equivalent) to disallow access to .svn directories. If you can't do the above, run an svn export through ssh instead (so it won't be a 'working copy'), but this will naturally be slower than doing an up.
Also, you can look at what Ruby on Rails does with Capistrano.. it's the same basic concept but supports transactional backups if the update goes wrong in the middle by storing each checkout in a separate folder and symlinking the "latest" to your /www directory.
A: The keywords stuff will fail in plenty of cases -- like if you've modified the source before deploying, or if you check in from one directory in your project then a different directory in the same project will have different revision numbers. Check the docs carefully to make sure the keywords do what you think they do.
The better way is to use the svnversion program to generate information about your checked out directories at compile or deployment time. Svnversion will show information about the version of ALL of your directories as well as flagging whether or not the source was locally modified.
A: The method I've come up for my php projects, may not be the best method but after some time searching certainly seems to be, is to do a checkout, run a version check, wipe out the .svn folders, and move on. Here is a portion of shell script I've written:
(first, you need the script the checkout your repo)
# get the svn revision number and create a RELEASE file
svnvers=`svnversion .`
echo "version: $svnvers"
echo "<release><development>0</development><revision>$svnvers</revision></release>" > RELEASE
# remove all .svn directories
find . -name .svn -exec rm -rf {} \;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Simple/lightweight alternative to GNU Mailman? I'm looking for a dead simple mailing list (unix friendly). Robustness, fine-grained configurability, "enterprise-readiness" (whatever that means) are not requirements. I just need to set up a tiny mailing list for a few friends. Rather than hack something up myself, I was wondering if anybody knows of anything already out there with a similar goal?
I should note right now that I don't want an externally hosted mailing list -- it needs to be software I can install and run on my server. I know of many places I can host a mailing list at (Google/Yahoo groups), but it would be nice to keep the data local.
A: Mailman is one of the simplest mailing list packages I've come across, so if Mailman is more than you want to deal with I'd suggest just adding an entry into /etc/aliases for your mailing list.
Of course you have to manage it by hand, but you said it's only for a few friends so that may not be a problem. Just create an entry in /etc/aliases such as:
mylist: [email protected], [email protected], \
[email protected]
and then run newaliases. It doesn't get much simpler than that. If you want an archive you can create a dummy account on your mail server and add them to the list.
It's not as user friendly as Mailman but it's simple and you can be up and running in 5 minutes.
A: If you're not afraid of perl, give Minimalist a try.
A: If you want something easy to setup, with a user interface on top then I would recommend to check out WP Mailster (WordPress plugin) or Mailster (Joomla plugin).
No matter which of the two CMS you prefer, you will only need 5 minutes to have a "naked" WordPress or Joomla and the plugin installed.
It really works well and is easy to use. I have used Mailster for years and recently, with my site's move to WordPress have switched wo WP Mailster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Any successful profibus communications from .NET? Has anyone successfully talked profibus from a .NET application?
If you did, what device/card did you use to accomplish this, what was the application, and did you use any kind of preexisting or available code?
A: We've not used Profibus, but have used DeviceNET (another CAN based protocol), Ethernet/IP and ControlNet which all have similar challenges.
We've been doing this since the late 1990's and therefore rely mainly on our own generated code using off-the-shelf hardware. The companies that have shown longevity during that period that I remember are:-
*
*AnyBus (HMS, www.anybus.com) we've recently started using their gateway products as we can place fieldbus interfaces close to the hardware and then communicate over normal Ethernet (usually using Ethernet/IP www.odva.org). This has the advantage of separating hardware and PC using only a network cable. The Ethernet/IP .NET classes were written by ourselves as nothing much was on the market at the time. I'm sure a quick google search would find suitable class libraries
*SST (www.mysst.com) have had fieldbus interfaces for more than a decade. The last SST card we used for DeviceNET still only had VB6 sample code. A good selection of fieldbus support and different form-factors e.g. PC104, PCI, PMCIA
*Beckhoff/Wago (www.beckhoff.com, www.wago.com) we typically use Beckhoff for the I/O more than the interface cards but again a company that has been around a long time. They also have products that support exposing using OPC (another way for you to get I/O information without directly communicating with the hardware/devicedrivers)
I suggest not using OPC interfaces to the hardware directly (it’s OK for communication using PC (.NET)->PLC->Profibus) as you need to ensure that the control system responds to loss of control from your .NET application. I’m assuming that you are needing a profibus Master here (not a slave), so as long as your control system is intrinsically fail safe, then loss of communication should mean the control system enters an "Idle" state and therefore most of the I/O will return to the fails safe state.
We also try to ensure that we do not put safety related code in .NET. Most of our .NET code is userinterface from a PLC, but in some places we do control the fieldbus directly but ensure hardware interlocks will prevent un-safe operation, either using safety switches/relays or a small PLC with the the task of interlocking only. And above all make the system fail-safe! Loss of comms from the .NET code should shutdown the automation to the fail-safe state.
A: We have used Steeplechase to connect to our profibus to our automated pick system.
http://www.phoenixcontact.com/automation/32131_31909.htm
A: Try this: http://libnodave.sourceforge.net
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: EDI Converter Tool 850 to 940 I need to convert an x12 850 v4010 to a x12 940 v4010. Most of the tools convert from x12 to xml then I would need to map the xml to a 940. I am hoping there is a tool that could convert from one edi document to another.
EDIT FOR INFORMATION:
Quick Background
Electronic Data Interchange (EDI) is
classically defined as the
application-to-application exchange of
structured business data between
organizations. X12 is an ANSI standard
that supplies that structure. There
are many good books concerned with the
business benefits of EDI,
implementation considerations, and
operational aspects
A: Going to give Altova MapForce and Stylus Studio® a try.
http://www.altova.com/downloadtrialmapforce3.html
http://www.stylusstudio.com/xml_product_index.html
A: Mapping from one doc to another nearly always involves making a number of assumptions that are only probably true, and probably isn't usually good enough when you're talking about moving money around.
A: Servingxml library is also worth looking at, compared to Altova and Stylus it is FOC.
It is able to parse EDI to XML and back, by chaining the steps together. Can be called from command line or embedded (written in Java).
There is a lot of examples how to convert plain text to XML and back.
The con compared to Altova and Stylus is probably lack of development GUI, you must declare the mapping by hand in XML-based configuration file.
A: Also look at Symphonia software by Orion. It is commercial software but does what you want.
A: I was project manager for something called EdiMatch when I worked for adra match asa (Norwegian company, I think it's at http://adramatch.com) which could read EDI files and then you would get "concrete objects" (COM, Windows only though) back which you could serialize into "whatever" you wish later...
I know they licensed it out to at least Agresso (Norwegian ERP vendor) back when I worked for them. I think they would be interested in licensing it out still to others, but not sure...
A: I think the problem may be that the 850 won't have all the information necessary to correctly complete a 940. I never used a 940, but did use 856's (Advanced Ship Notice) a lot, which look to be similar to the 940. The 850 will contain information about the order (SKUs, quantities, ship to addresses, etc), but not information about how it was shipped (carrier, tracking ids, ship date, weights, packaging, etc). This information usually needs to be provided at the time of shipment, and combined with the information from the 850 to create a 940.
There are some documents (like the 997) which can be created from a document with no 'outside assistance'. But I would be surprised if the 940 is one of them.
A: Is this a one time conversion or part of a process?
there are a few enterprise integration tools you can use like BizTalk.
Otherwise, If you can get a hold of the BizTalk 2006 R2 EDI schemas then you could have the XML representation of both documents. Then you could read the nodes for the segments that are common and copy those. I have not used a 940 before, but i am familiar with 810, 309 and its related documents, and 997; but you might have to fill in some of the data yourself to complete the 940 document.
A: If you are willing to use a software package to do your EDI to EDI conversion, I would recommend using Softshare Delta. It is actually a great product that I've used for several years. It will take care of your translation needs, but it isn't free.
A: I see three issues here. First, mapping between the purchase order and a warehouse shipping order. The data doesn't match up exactly, but if you assume a one-to-one relationship between a purchase order and a shipping order, then that can be overcome. I assume you can hard-code data like the warehouse id, hazardous materials codes, etc.
The second problem is do you need one-time, or occasional transformation which you will do manually, or runtime translation that you set up once and integrate into a translation system?
Third is based on that, what tool to use? Either way, I would take a good look at Stylus Studio. It has both an IDE for local testing or manual conversion, and a runtime component that you install on a server. My former company used it extensively, and it's cheaper than almost any other real-time translator (Mercator, Gentran, etc.)
To use Stylus, you'll import the source file (the 850) and create a reusable schema which can be used to parse the file into XML. Then, import an example of the output format (the 940) to create a schema which can be used to serialize the document back into X12.
From there, you can use the mapping tools to get you close, then hand-edit the XSLT for complicated logic which may need to be tweaked (loops aren't perfectly handled, for instance). Stylus Studio even allows you to create "pipelines" which can be used to chain multiple XSLT maps in a row, or pull in data from outside sources into the middle of a translation.
Then, you can wrap all that up and export it to your realtime environment. Better yet, if you're doing this manually, you can just run your files through the pipeline as you get them, and you'll be done.
A: I would like to try out ALTOVA's mapforce tool to convert EDI 850 X12 to Oracle Apps. Is this a good choice.
I hear that the most popular is http://www.sterlingcommerce.com/, but it is very costly..
Please advice
Shashi
A: in bots open source edi translator you can map 850 v4010 to a x12 940 v4010 (http://bots.sourceforge.net).
basically and input can be mapped to any output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are there any tools to visualize a RDF graph? (please include a screenshot) I'm looking for a tool that will render a RDF graph in a reasonably useful graphic format. The primary purpose of the graphic format being inclusion into a PowerPoint slide or printing on a large plotter for management review.
I am currently using TopBraid Composer which does a reasonably well at visualizing a single entity but doesn't seem to have a clear way of visualizing the entire graph (as a whole).
Anyone know of any good solutions to this problem?
A: I was looking for one too and i found this : https://gephi.org/
Pretty sure it works with rdf.
A: Protégé.
Activate Tools > Tabs > Jambalaya.
(source: utexas.edu)
A: WebVOWL is a great choice for visualizing ontologies. http://vowl.visualdataweb.org/webvowl.html
A: -Cytoscape http://www.cytoscape.org/ works well with large scale graphs and you can create a static pdf or image.
-I also found this very interesting http://d3js.org/
It's not specific to RDF graphs, but in the examples there seems to be some cool functionality where the users could have a large degree of interaction with the data. It does however require a fair amount of JS programming knowledge.
A: RDFShape which is also based on Graphviz can be useful to visualize small RDF graphs for presentations. It allows both SVG and PNG output formats. An example visualization can be this one
A: The Perl utility rdfdot, based on Graphviz, and this library, might help:
http://metacpan.org/pod/RDF::Trine::Exporter::GraphViz
https://github.com/nichtich/RDF-Trine-Exporter-GraphViz
Graphviz is able to handle thousands of nodes, and therefore might suit the scale of your problem..
A: Commandline with rapper and graphviz:
$ rapper --input ntriples $fname.nt --output dot > $fname.dot
$ dot -Tpng $fname.dot > $fname.png
A: Gephi was already mentioned, but I'll incode screenshots and a short description here.
Gephi can not just visualize graphs but also supports analyzing, layouting and further importing and exporting. There is a Semantic Web Import Extension that allows you to directly query (via SPARQL) or import RDF data. https://wiki.gephi.org/index.php/SemanticWebImport (You can install it directly within the program at Plugins.
There's a JavaScript Graph Visualisation Library which worked quiet nice for me: http://sigmajs.org/ It works well together with Gephi since you can Export your graph from there and import the file into SigmaJS. That way you can export your graph to an interactive web site. Example: http://fannon.de/p/smw/vis/George_Orwell_Platz_30.html
An important mention would be D3.js which has already dozends of force graph examples. But it doesn't support RDF directly, so the data has to be converted first.
A nice one is this: http://nylen.tv/d3-process-map/graph.php?dataset=les-mis
A: RDF Gravity is an RDF visualisation tool.
Here's a screenshot:
(source: salzburgresearch.at)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Error Tolerant HTML/XML/SGML parsing in PHP I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML
<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>
I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML.
My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file.
$oDom = new DomDocument();
$oDom->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>");
//gives us
DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in ....
The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name).
Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP?
(if it's not obvious, I don't consider regular expressions a valid solution here)
Update: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.
A: You can suppress warnings with libxml_use_internal_errors, while loading the document. Eg.:
libxml_use_internal_errors(true);
$doc = new DomDocument();
$doc->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>");
libxml_use_internal_errors(false);
If, for some reason, you need access to the warnings, use libxml_get_errors
A: I wonder if passing the "bad" HTML through HTML Tidy might help as a first pass? Might be worth a look, if you can get the document to be well formed, maybe you could load it as a regular XML file with DomDocument.
A: @Twan
You don't need a DTD for DOMDocument to parse custom XML. Just use DOMDocument->load(), and as long as the XML is well-formed, it can read it.
Once you get the files to be well-formed, that's when you can start looking at XML parsers, before that you're S.O.L. Lok Alejo said, you could look at HTML TIDY, but it looks like that's specific to HTML, and I don't know how it would go with your custom elements.
I don't consider regular expressions a valid solution here
Until you've got well-formedness, that might be your only option. Once you get the documents to that stage, then you're in the clear with the DOM functions.
A: Take a look at the Parser in the PHP Fit port. The code is clean and was originally designed for loading the dirty HTML saved by Word. It's configured to pull tables out, but can easily be adapated.
You can see the source here:
http://gerd.exit0.net/pat/PHPFIT/PHPFIT-0.1.0/Parser.phps
The unit test will show you how to use it:
http://gerd.exit0.net/pat/PHPFIT/PHPFIT-0.1.0/test/parser.phps
A: My quick and dirty solution to this problem was to run a loop that matches my list of custom tags with a regular expression. The regexp doesn't catch tags that have another inner custom tag inside them.
When there is a match, a function to process that tag is called and returns the "processed HTML". If that custom tag was inside another custom tag than the parent becomes childless by the fact that actual HTML was inserted in place of the child, and it will be matched by the regexp and processed at the next iteration of the loop.
The loop ends when there are no childless custom tags to be matched. Overall it's iterative (a while loop) and not recursive.
A: @Alan Storm
Your comment on my other answer got me to thinking:
When you load an HTML file with DOMDocument, it appears to do some level of cleanup re: well well-formedness, BUT requires all your tags to be legit HTML tags. I'm looking for something that does the former, but not the later. (Alan Storm)
Run a regex (sorry!) over the tags, and when it finds one which isn't a valid HTML element, replace it with a valid element that you know doesn't exist in any of the documents (blink comes to mind...), and give it an attribute value with the name of the illegal element, so that you can switch it back afterwards. eg:
$code = str_replace("<pseudo-tag>", "<blink rel=\"pseudo-tag\">", $code);
// and then back again...
$code = preg_replace('<blink rel="(.*?)">', '<\1>', $code);
obviously that code won't work, but you get the general idea?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Installing Svn 1.5.x on Debian Etch - Best approach? How do you install svn 1.5 on debian etch? The svn 1.5 packages available for etch are 1.4 and I really need the cool new merge tracking feature in svn1.5 (according to CollabNet its as good as ClearCase...an interesting statement in oh so many ways). So, what's the least painful way to go?
My options are:
*
*build it from source
*create my own debian package
*upgrade to a test version of Lenny
*find someone else's svn 1.5 package
Which one have you chosen or which do you think has the least amount of suffering?
A: Have you considered pinning? Basically, you can upgrade some of your system (i.e. just Subversion and its dependencies) to Lenny, while keeping the rest as Etch.
A: It depends on whether you want to be able to upgrade Subversion in future using Debian's package management tools. Building it from source should be easy enough, and lets you configure it the way you want, but then each time you want to upgrade, you'll need to build it from source again, rather than a simple apt-get.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I create a new signal in pygtk I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
A: Here is how:
import gobject
class MyGObjectClass(gobject.GObject):
...
gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,
None, (str, int))
Where the second to last argument is the return type and the last argument is a tuple of argument types.
A: If you use kiwi available here you can just do:
from kiwi.utils import gsignal
class MyObject(gobject.GObject):
gsignal('signal-name')
A: You can also define signals inside the class definition:
class MyGObjectClass(gobject.GObject):
__gsignals__ = {
"some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
}
The contents of the tuple are the the same as the three last arguments to gobject.signal_new.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Unhandled exception logging for Windows Forms Is there anything like ELMAH for Windows Forms?
I'm looking for a standard way to process unhandled exceptions and grab a screenshot and other environment information before packaging that up for support.
A: The very same Jeff Atwood coded a nice solution (albeit in VB.NET) which I had to modify and "fix" but that I am happily using since then.
You can view his solution Here
A: There is a nice User Friendly Exception Handling made by Jeff Atwood in 2004. I used it for several of our internal applications and it worked well.
A: There is a commercial alternative called {smartassembly} that does error reporting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: IMAP4 server for .NET Are there any free (non-GPL) libraries for .NET that provide IMAP4 server side functionality?
E.g. handles the socket level and message handshaking so that an IMAP4 client (such as outlook) can retrieve, read, edit and/or delete messages.
I am not trying to connect to an IMAP4 server, I'd like the assistance to implement one.
A: I know I'm answering my own question, but after yet more searching I think I may have found something matching my needs:
NMail
Features
*
*NMail is a 100% .net application.
*A Windows installer and setup wizard.
*ASP.net Webmail.
*An ASP.net administration site.
IMAP Server Features
*
*Support for ACLs.
*NTLM authentication (Secure Password Authentication (SPA) under Outlook and Outlook Express).
*Support for SSL/TLS encryption.
*SASL plain authentication support (when using an encrypted session).
SMTP Server Features
*
*Support for SSL/TLS encryption.
*Flexible API for filtering and altering messages. E.g. To remove spam or to rewrite addresses, etc.
A: I'm not sure if you have tried Indy (previously a set of Delphi components) - although I am not sure if they do IMAP4 as their web page is a bit blank, as is their CodePlex hub. Go to their website. Other than that I'm not sure - even Google only shows clients.
A: You can check Lumisoft Mail Server. The license is FREEWARE.
General:
* SMTP/POP3/IMAP4/WebMail
* IP access filtering
* User mailbox size limit
* Supports XML or MSSQL databases
* Nice GUI for administation
* Well commented source code included
SMTP:
* All basic smtp features
* Supports multiple domains
* Supports multiple e-address for one mailbox
* Supports aliases(Mailing lists). Supports public and private
(needs authentication) lists.
* Supports email routing. eg *ivar* pattern routes all addresses containing
ivar to specified mailbox or remote address
* SMTP AUTH (LOGIN CRAM-MD5) (supported authentication types)
* SMTP SIZE, PIPELINING, 8BITMIME, CHUNCKING support
* SMTP custom message filters
* Relay can be controlled by IP access or authentication
POP3:
* All basic pop3 features
* APOP command for secure authentication
* POP3 AUTH (LOGIN CRAM-MD5) (supported authentication types)
* POP3 remote accounts
WebMail (ASP.NET):
* Standalone webmail, can be used any with IMAP based mailserver
* Supports XML or MSSQL databases
* Multiple UI languages
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to control the capitalization of month and day names returned by DateFormat? Here is a quick test program:
public static void main( String[] args )
{
Date date = Calendar.getInstance().getTime();
System.out.println("Months:");
printDate( "MMMM", "en", date );
printDate( "MMMM", "es", date );
printDate( "MMMM", "fr", date );
printDate( "MMMM", "de", date );
System.out.println("Days:");
printDate( "EEEE", "en", date );
printDate( "EEEE", "es", date );
printDate( "EEEE", "fr", date );
printDate( "EEEE", "de", date );
}
public static void printDate( String format, String locale, Date date )
{
System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) );
}
The output is:
Months:
en: September
es: septiembre
fr: septembre
de: September
Days:
en: Monday
es: lunes
fr: lundi
de: Montag
How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.
A: Capitalisation rules are different for different languages. In French, month names should not be capitalised.
A: You may not want to change the capitalization -- different cultures capitalize different words (for example, in German you capitalize every noun, not just proper nouns).
A: tl;dr
How can I control the capitalization of the names
You don’t. Different languages and different cultures have different rules about capitalization, punctuation, abbreviation, etc.
getDisplayName — automatically localize
Month.from( LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) ) // Get current month.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Localize automatically. Specify `Locale` to determine human language and cultural norms for translation.
février
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) // Get current date as seen by people in a certain region (time zone).
.getDayOfWeek() // Get the day-of-week as a pre-defined `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH )
lundi
Localize
As others stated, you should not be forcing your own parochial (US English?) notions of capitalization. Use a decent date-time library, and let it automatically localize for you.
java.time
You are using terrible old date-time classes that are now legacy, supplanted by the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" );
LocalDate today = LocalDate.now( z );
To work with a month, extract a Month enum object. Ditto for day-of-week, DayOfWeek.
Call getDisplayName. Pass a TextStyle for abbreviation. Pass a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such. Note that Locale has nothing to do with time zone.
Month m = today.getMonth() ;
String mNameQuébec = m.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
String mNameGermany = m.getDisplayName( TextStyle.FULL , Locale.GERMANY ) ;
…and…
DayOfWeek dow = today.getDayOfWeek() ;
String dowNameQuébec = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
String dowNameGermany = dow.getDisplayName( TextStyle.FULL , Locale.GERMANY ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
*
*Java SE 8, Java SE 9, and later
*
*Built-in.
*Part of the standard Java API with a bundled implementation.
*Java 9 adds some minor features and fixes.
*Java SE 6 and Java SE 7
*
*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
*Android
*
*Later versions of Android bundle implementations of the java.time classes.
*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
A: Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it...
about.com on french capitalization
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Are there any advantages compiling for .NET Framework 3.5 instead of 2.0? Are there any advantages compiling for .NET Framework 3.5 instead of 2.0?
For example less memory consumption, faster startup, better performance...
Personally I don't think so however, I may have missed something.
Edits
*
*Of course there are more features in the 3.5 framework, but these are not the focus of this question.
*There seem to be no advantages.
*Yes I meant targeting the Framework. I have installed the latest 3.5 SP1 and VS 2008 so what's the difference between compiling with and targeting a framework? I can target the framework in the project options but how do I 'compile with' a specific framework version? I did not know that there is a difference.
*So for now we agree that there are no advantages.
A: There's a difference between compiling and targeting.
Compiling the code with the (for example) C# 3.0 compiler will probably give you a boost on performance (very little one anyway) as some optimization for the generated IL code migh have been included. It also allows you to use some of the new features like automatic properties or lambda expressions.
Targeting for a given framework will ensure your assembly works for that framework (and posteriors) and will fail if you target for 2.0 and are using a 3.5 library. No performance improvements will be directly related to that unless your substituting a class from one framework with another "fastest" class. For example, targeting .NET 1.1 won't allow you to use generics and therefore you'll have to use the ArrayList which is considerably slower than List (due to boxing and unboxing).
A: There are two things to remember in regards to .NET 2.0 and .NET 3.5.
*
*The .NET Framework 3.5 is just a few libraries that run on top of .NET 2.0.
*When developing in Visual Studio 2008 and targeting .NET 2.0 you can still use certain C# 3.0 language features such as Extension Methods since they are in fact a feature of the C# 3.0 (or .NET 3.5) compiler. See this link: http://www.codethinked.com/post/2008/02/Using-Extension-Methods-in-net-20.aspx
A: I haven't found any. An obvious disadvantage, if you don't need the 3.5 specific features, is that the 3.5 code base is younger and is therefore possible, albeit unlikely, that there is some bug lurking around.
A: There is no benefit to compiling to the 3.5 framework if you are not using any classes from that version of the framework.
A: I presume that you must mean targeting the .NET 3.5 framework for your compilation? If so then as others have said I don't believe you will see much difference.
However, if you're talking about using the updated compilers then there are various changes and break changes described for both C# and VB at the following links:
*
*C# 3.0 and SP1 compiler
chanages
*What's New in the Visual Basic
Compiler
*Visual Basic 2008 Breaking
Changes
A: I believe that a different compiler ships with each version of Visual Studio. For example in the case of C# the 2.0 compiler shipped with Visual Studio 2005 and the C# 3.0 shipped with Visual Studio 2008. Depending upon which version of Visual Studio you use you end up with a different compiler.
Targeting a framework refers to specifically which version of the framework you wish to target during the compilation process; targeting frameworks is a new feature of Visual Studio 2008. For instance I could have a solution open in Visual Studio 2008 and target v2.0 of .Net. The result would be that I wouldn't have any of the 3.0 or 3.5 .Net features available to me during that compilation, for example WPF.
A: If your .NET assembly targets .NET 3.5, the resulting application will look for and require the .NET 3.5 libraries, and that's that. These libraries come with numerous additional classed not found in the .NET 2.0 framework, so that would be the advantage to targetting those libraries.
If you however compile C# code with the C# 3.0 compiler shipping with e.g. Visual Studio 2008 and suited for .NET 3.5, but have your assembly target .NET 2.0, you will still only need the regular .NET 2.0 libraries, and despite this actually use certain .NET 3.5 compiler features, as a number of those features are only making use of .NET 2.0 code in the end. Read more about this here: http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx
A: 3.5 has classes that 2.0 doesn't. Func<...> for instance. If you aim for 2.0, you can't use them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Java Servlet 404 errors What culprits are the most likely to cause a 404 resource not found error when a page in a given .WAR, autocreated by Sun's J2EE deploytool, is trying to load a Servlet in the same .WAR file?
Eg:
HTTP Status 404 - /MyServlet/MyServlettype Status reportmessage /MyServlet/MyServletdescription The requested resource (/MyServlet/MyServlet) is not available.
Related: Of these, how many would you expect to be server specific? eg: Sun Java Application Server vs Tomcat & Catalina ?
A: Is there a valid <servlet-mapping> for 'MyServlet' in your web.xml? That's been my number one culprit in the past
A: A 404 error means that the requested resource was not found. As pkaeding suggests, it is probably due to the servlet mapping not being correct (or not being present) in the web.xml file. Servlets must be specified in the web.xml file, and not only that, but they must be mapped to particular paths (an "url-mapping"). If the "MyServlet" servlet exists, but is not mapped to a path that may resolve with "/MyServlet/MyServlet" based on the application context root, and nothing else (i.e. another servlet, etc) resolves with this path, the application server will throw a 404 stating that nothing is mapped to the given path.
A: I just spent about an hour pulling my hair out on this very problem. Tomcat 5.5.27 on OSX was working just fine until I'd added another servlet and servlet-mapping at which point everything was returning a 404. I hadn't realized it, but when I'd added a new servlet/servlet-mapping pair I'd put the servlet-mapping before the servlet entry. It's an easy mistake to make and, although knee-capping the entire application without giving anything resembling a sensible error message seems a little extreme, it makes perfect sense in retrospect.
A: Servlet mapping is a common problem. But if you have any fitlers in your web.xml those can be the culprit as well. One thing to realize is filters always execute the code before the doFilter before any servlets starts executing. (Technically filters execute code after the doFilter) In our code we created filters that would return 404 under certain situations. Sometimes removing some or all filters-mapping will help discover if it is related to filter-mappings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why is RSpec so slow under Rails? Whenever I run rspec tests for my Rails application it takes forever and a day of overhead before it actually starts running tests. Why is rspec so slow? Is there a way to speed up Rails' initial load or single out the part of my Rails app I need (e.g. ActiveRecord stuff only) so it doesn't load absolutely everything to run a few tests?
A: Why is rspec so slow? because it loads all the environement, loads fixtures and all that jazz.
Is there a way to speed up Rails' initial load you could try using mocks instead of relying on the database, this is actually correct for unit testing and will definitly speed up your unit tests. Additionnaly using the spec server as mentionned by @Scott Matthewman can help, same with the autotest from zentest mentionned by @Marc-Andre Lafortune
Is there a way to single out the part of my Rails app I need (e.g. ActiveRecord stuff only) so it doesn't load absolutely everything to run a few tests? what about this
rake test:recent
I am not sure how the rspec task integrate with this but you could definitely use the test:recent task as a template to do the same with rspec tests if the.
rake test:rspec:recent
doesn't exist yet
A:
because it loads all the environement, loads fixtures and all that jazz.
The real culprit is if you run it using rake spec, it runs the db:test:prepare task.
This task drops your entire test database and re-creates it from scratch. This seems ridiculous to me, but that's what it does (the same thing happens when you run rake:test:units etc).
You can easily work around this using the spec application which rspec installs as part of the rspec gem.
Like this:
cd railsapp
spec spec # run all specs without rebuilding the whole damn database
spec spec/models # run model specs only
cd spec
spec controllers/user* # run specs for controllers that start with user
A: I think the "zen" experience you're looking for is to run spec_server and autospec in the background, with the result being near-instant tests when you save a file.
However, I'm having problems getting these two programs to communicate.
I found an explanation here:
I've noticed that autotest doesn't send commands to the spec_server.
Instead it reloads the entire Rails environment and your application's
plugins everytime it executes. This causes autotest to run
significantly slower than script server, because when you run the
script/spec command the specs are sent to the spec_server which
already has your Rails environment fired up and ready to go. If you
happen to install a new plugin or something like that, then you'll
have to restart the spec_server.
But, how do we fix this issue? I'm guessing it would involve downloading ZenTest and changing code for the autotest program, but don't have time to try it out right now.
A: I definitely suggest checking out spork.
http://spork.rubyforge.org/
The railstutorial specifically addresses this, and gives a workaround to get spork running nicely in rails 3.0 (as of this moment, spork is not rails 3 ready out of the box). Of course, if you're not on rails 3.0, then you should be good to go.
The part of the tutorial showing how to get spork running in rails 3.0
http://railstutorial.org/chapters/static-pages#sec:spork
Checking when spork is rails 3.0 ready
http://www.railsplugins.org/plugins/440-spork
A: Are you running this over Rails? If so, it's not RSpec's initialization that's slow, it's Rails'. Rails has to initialize the entire codebase and yours before running the specs. Well, it doesn't have to, but it does. RSpec runs pretty fast for me under my small non-rails projects.
A: Running tests can be really slow because the whole rails environment has to load (try script/console) and only then can all tests run. You should use autotest which keeps the environment loaded and will check which files you edit. When you edit and save a file, only the tests that depend on these will run automatically and quickly.
A: You should be able to to speed up your script/spec calls by running script/spec_server in a separate terminal window, then adding the additional -X parameter to your spec calls.
A: If you're using a Mac I recommend using Rspactor over autotest as it uses a lot fewer resources for polling changed files than autotest. There is both a full Cocoa version
RSpactor.app
or the gem version that I maintain at Github
sudo gem install pelle-rspactor
While these don't speed up individual rspec tests, they feel much faster as they auto run the affected spec's within a second of you hitting save.
A: As of rspec-rails-1.2.7, spec_server is deprecated in favor of the spork gem.
A: The main reason is that require takes forever on windows, for some reason.
Tips for speedup:
spork now works with windows, I believe.
You can try "faster_require" which caches locations:
http://github.com/rdp/faster_require
GL.
-rp
A: If you are on a Windows environment then there is probably little you can do as Rails seems to startup really slowly under Windows. I had the same experience on Windows and had to move my setup to a Linux VM to make it really zippy (I was also using autotest).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Add a linebreak in an HTML text area How can i add a line break to the text area in a html page?
i use VB.net for server side coding.
A: If it's not vb you can use 
 (ascii codes for cr,lf)
A: You could use \r\n, or System.Environment.NewLine.
A: If you're inserting text from a database or such (which one usually do), convert all "<br />"'s to &vbCrLf. Works great for me :)
A: In a text area, as in the form input, then just a normal line break will work:
<textarea>
This is a text area
line breaks are automatic
</textarea>
If you're talking about normal text on the page, the <br /> (or just <br> if using plain 'ole HTML4) is a line break.
However, I'd say that you often don't actually want a line break. Usually, your text is seperated into paragraphs:
<p>
This is some text
</p>
<p>
This is some more
</p>
Which is much better because it gives a clue as to how your text is structured to machines that read it. Machines that read it include screen readers for the partially sighted or blind, seperating text into paragraphs gives it a chance of being presented correctly to these users.
A: Add a linefeed ("\n") to the output:
<textarea>Hello
Bybye</textarea>
Will have a newline in it.
A: I believe this will work:
TextArea.Text = "Line 1" & vbCrLf & "Line 2"
System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.
A: Escape sequences like "\n" work fine ! even with text area! I passed a java string with the "\n" to a html textarea and it worked fine as it works on consoles for java!
A: Here is my method made with pure PHP and CSS :
/** PHP code */
<?php
$string = "the string with linebreaks";
$string = strtr($string,array("."=>".\r\r",":"=>" : \r","-"=>"\r - "));
?>
And the CSS :
.your_textarea_class {
style='white-space:pre-wrap';
}
You can do the same with regex (I'm learning how to build regex with pregreplace using an associative array, seems to be better for adding the \n\r which makes the breaks display).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: Where is a good place to start with making an application in .NET that communicates through OPC? Where is a good place to start with making an application in .NET that communicates through OPC?
A: You can find a good article and a library to start with here: http://www.codeproject.com/KB/COM/opcdotnet.aspx
A: The Code Project article is from the early days of .NET and may not be the best option today.
Alternatives include OPC Foundation's own .NET API (requires OPC Foundation membership) or several commercial products. OPCconnect.com lists a number of these.
A: Be careful. I haven't used an OPC API yet that properly conforms to any sort of calling conventions, particularily in the area of freeing memory (COM, as documented, or otherwise). Expect a month of debugging memory leaks.
A: SoftwareToolbox's OPCData.NET (http://www.opcdata.net/) claims to be a 100% Managed code solution for OPC Client. SoftwareToolbox also has some other OPC libraries to help with binding OPC data to forms and web interfaces.
A: If buying a comercial toolkit is an option I've used the Northern Dynamics server toolkit and it worked fine. A toolkit will take away a lot of the issues mentioned in the other questions (or at least you should get support if there's a problem).
They've wrapped the OPC protocol up nicely so it makes it easy to use. See one of my questions here for a type-safe Variant wrapper that I wrote to help with this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Trying to understand web services performance I bought an ASP.NET script about a year ago to retrieve FedEx shipping values. It builds an XML string that passes to the FedEx server using an HttpWebRequest, then parses the raw XML. The average response time for the script is about 900 milliseconds.
So the other day I was poking around in the FedEx developer center and discovered that they provide some C# code samples for using their web service. I built a little project using their code and WSDL file, and was surprised to find that the average response time is about 2.5 seconds.
Can someone help me understand the difference in speed? And is there a way to make it faster? I have zero experience using web services.
Thanks.
A: Web Services have some overhead with respect to XML over HTTP calls because of validation and what is called the "SOAP envelope", which adds some extra verbosity.
That said, I don't think the bigger response time is due to that. Did you try running the XML over HTTP version today to have a reasonable comparison point? Maybe the site is just busy.
One other explanation could be bad coding. You never know.
A: Well, the ASP.NET script could be doing something different than the C# code. Try capturing each raw HTTP request and playing them back. Do they perform the same? If so, then it is likely differences in the client code. My guess is that one is a straight HTTP get/post request, the other SOAP over HTTP(s).
Other things to look at:
1) Are you hitting production for ASP.NET and test system for C#, or are they both production?
2) Assuming both are over HTTPS.
A SOAP-based web service is typically a little more "heavy weight" -- especially if your request ends up doing WS-*, signing, etc. Do you have to sign your C# request by providing keys/x.509 or other credentials?
There are many ways this discussion could go depending on answers to a few of the basics above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Promising alternatives to make? I've been using make and makefiles for many many years, and although the concept
is sound, the implementation has something to be desired.
Has anyone found any good alternatives to make that don't overcomplicate
the problem?
A: Be aware of the ninja build tool (v1.8.2 Sept 2017) which is influenced by tup and redo.
The build file generator cmake (e.g. for Unix Makefiles, Visual Studio, XCode, Eclipse CDT, ...) can also generate ninja build files since version 2.8.8 (April 2012) and, afaik, ninja is now even the default build tool used by cmake.
It is supposed to outperform the make tool (better dependency tracking and is also parallelized).
cmake is an already well-established tool. You can always choose later the build tool without modifying your configuration files. So if a better build is developed in the future which will be supported by cmake you can switch to it conveniently.
Note that for c/c++ improving compilation time is sometimes limited because of headers included through the preprocessor (in particular when using header-only libs, for instance boost & eigen) which hopefully will be replaced by the proposal of modules (in a technical review of c++11 or eventually in c++1y). Check out this presentation for details on this issue.
A: I wrote a tool called sake that tried to make writing makefile-like things very easy to read and write.
A: It sort of depends on what you're trying to do. If all you want is make-style target dependencies and command invocation, then Make is actually one of the better tools for the task. :-) Rake is very nice, but can be clumsy for some simple cases. Ant is of course verbosity city, but it has better support for building Java-like languages (Scala and Groovy included). Also, Ant is available everywhere. That's the main reason I use it. Because it works consistently on Windows, it's actually even more cross-platform than Make.
If you want dependency management for Java-like libraries, Maven is the canonical choice, but I personally like Buildr a lot better. It's faster and much easier to customize (it's based on Rake). Unfortunately, it isn't quite as ubiquitous as Maven just yet.
A: check out SCons. For example Doom 3 and Blender make uses of it.
A: I still prefer make after having considered a bunch of the alternatives. When you auto-generated dependencies either via the compiler or something like fastdep there is not much left to do. In particular I do not want my build script to be tied to the implementation language, and I don't like writing stuff in XML when more readable alternatives are available. A tool that expose a general purpose language has merit though, but yet another interpreted language does not (afaik). What is Wrong with Make? might appeal to your point of view about moving away from make.
/Allan
A: I have a lot of friends who swear by CMake for cross-platform development:
http://www.cmake.org/
It's the build system used for VTK (among other things), which is a C++ library with cross-platform Python, Tcl, and Java bindings. I think it's probably the least complicated thing you'll find with that many capabilities.
You could always try the standard autotools. Automake files are pretty easy to put together if you're only running on Unix and if you stick to C/C++. Integration is more complicated, and autotools is far from the simplest system ever.
A: doit is a python tool. It is based in the concepts of build-tools but more generic.
*
*you can define how a task/rule is up-to-date (not just checking timestamps, target files are not required)
*dependencies can be calculated dynamically by other tasks
*task's actions can be python functions or shell commands
A: Ruby's make system is called rake: http://rake.rubyforge.org/
Looks quite promising.
There's always Ant: http://ant.apache.org, which I personally find horrendous. It's the de-facto standard for Java development, however.
A: I recommend using Rake. It's the easiest tool I've found.
Other good tools I've used, though, if Ruby's not your thing, are:
*
*AAP (Python)
*SCons (Python)
*Ant (Java, config in XML, pretty complex)
A: Some of the GNOME projects have been migrating to waf.
It's Python-based, like Scons, but also standalone -- so rather than require other developers to have your favorite build tool installed, you just copy the standalone build script into your project.
A: FlowTracer from RTDA is another good choice that I have seen used commercially in a large scale environment (tens of thousands of jobs): http://www.rtda.com/flowtracer-design-flow-infrastructure-software
It has a GUI which shows the dependency graph with color-coded boxes for jobs and ovals for files. When the number of jobs and files gets high, a GUI-based tool like FlowTracer is pretty much essential.
The initial setup cost is higher than Make. There's a learning curve for setting up your first flow using it. After that, it gets quicker.
A: I'm not sure if you are asking the correct question here.
Are you after a simplified make? In which case, you need to get someone who is very familiar with make to create a series of (M|m)akefiles that will simplify your problem.
Or are you wanting to look at the underlying technology? Are we wanting to enforce a design-by-contract type architecture which is built in to, and enforced in, the code design? Or possibly, the language itself, e.g. Ada and its concept of specs (interfaces) and bodies (implementations)?
Which direction you are after will definitely affect the potential results of such a question?
Basically, new ways of building systems from only those components that have really changed versus adoption of new technologies that have such mechanisms built in by design.
Sorry it's not a direct answer. Just wanted to try and get you to evaluate which path you wanted to head down.
cheers,
Rob
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
} |
Q: Custom style with Qt Has anybody experience in building a custom style in Qt? What I have in my mind is a complete new style that affects all kind of widgets. I have seen some examples in the web for a custom combo box. But I have no idea how much time and code it takes to build a "complete" new custom style ... maybe someone can give me a hint.
We think of using Qt 4.3 (or even newer) ...
A: Check out the Stylesheets facility in Qt 4. While it's still a hassle, it's way easier than doing a full-on custom style. You can just adjust one visual facet at a time and try it out.
It pays attention to inheritance. So if you style the font in QWidget, then every visual widget will also use that font. And so on.
A: I have developed a "new" style that changed the appearance of much of an application. It did take some time, and quite a bit of experimentation. I also derived my style from the generic windows style, to allow it to handle some of the stuff I didn't want to mess with. All told, I think it took me a week to get most of what I wanted, with practically no prior exposure to the styles.
In order to actually develop one, I would get into the source for their styles example, which has a "wood" style. I put my own style in place of the example style, and started changing things while using the example program to check how it looked. Depending on how you are developing it, you might want to have a configuration file so you can easily change some of the values without recompiling.
A: We've done it in the past (in Qt 3), and it's extremely time-consuming. We had a lot of problems with flickering, redraws not working the way we expected, sluggish behavior, bugs in the Qt implementation. It a lot less straight-forward than it seems, and there's little support or user experience too. Unless you need something really particular (as we did), I'd say it's not worth the trouble.
Other frameworks are supposed to make it easier (some Java-based?), but I don't have first hand experience.
A: You might want to look at existing styles. You can find quite a few of them on kde-look.org, in the Styles / 4.0 section.
A: If you don't need to radically change the widget style, you might want to try using widget style sheets:
http://doc.qt.digia.com/4.4/stylesheet.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Best way to represent a parameterized enum in C#? Are there any good solutions to represent a parameterized enum in C# 3.0? I am looking for something like OCaml or Haxe has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas?
See Ocaml example below in one of the replies, a Haxe code follows:
enum Tree {
Node(left: Tree, right: Tree);
Leaf(val: Int);
}
A: Not being familiar with OCaml or Haxe, and not being clever enough to understand the other explanations, I went and looked up the Haxe enum documentation - the 'Enum Type Parameters' bit at the bottom seems to be the relevant part.
My understanding based on that is as follows:
A 'normal' enum is basically a value which is restricted to the things that you have defined in your enum definition. C# Example:
enum Color{ Red, Green, Yellow, Blue };
Color c = Color.Red;
c can either be Red, Green, Yellow, or Blue, but nothing else.
In Haxe, you can add complex types to enums, Contrived example from their page:
enum Cell<T>{
empty;
cons( item : T, next : Cell<T> )
}
Cell<int> c = <I don't know>;
What this appears to mean is that c is restricted to either being the literal value empty (like our old fashioned C# enums), or it can also be a complex type cons(item, next), where item is a T and next is a Cell<T>.
Not having ever used this it looks like it is probably generating some anonymous types (like how the C# compiler does when you do new { Name='Joe'}.
Whenever you 'access' the enum value, you have to declare item and next when you do so, and it looks like they get bound to temporary local variables.
Haxe example - You can see 'next' being used as a temporary local variable to pull data out of the anonymous cons structure:
switch( c ) {
case empty : 0;
case cons(item,next): 1 + cell_length(next);
}
To be honest, this blew my mind when I 'clicked' onto what it seemed to be doing. It seems incredibly powerful, and I can see why you'd be looking for a similar feature in C#.
C# enums are pretty much the same as C/++ enums from which they were originally copied. It's basically a nice way of saying #define Red 1 so the compiler can do comparisons and storage with integers instead of strings when you are passing Color objects around.
My stab at doing this in C# would be to use generics and interfaces. Something like this:
public interface ICell<T> {
T Item{ get; set; }
ICell<T>{ get; set; }
}
class Cons<T> : ICell<T> {
public T Item{ get; set; } /* C#3 auto-backed property */
public Cell<T> Next{ get; set; }
}
class EmptyCell<T> : ICell<T>{
public T Item{ get{ return default(T); set{ /* do nothing */ }; }
public ICell<T> Next{ get{ return null }; set{ /* do nothing */; }
}
Then you could have a List<ICell<T>> which would contain items and next cell, and you could insert EmptyCell at the end (or just have the Next reference explicitly set to null).
The advantages would be that because EmptyCell contains no member variables, it wouldn't require any storage space (like the empty in Haxe), whereas a Cons cell would.
The compiler may also inline / optimize out the methods in EmptyCell as they do nothing, so there may be a speed increase over just having a Cons with it's member data set to null.
I don't really know. I'd welcome any other possible solutions as I'm not particularly proud of my one :-)
A: Use a class that with static properties to represent the enumeration values. You can, optionally, use a private constructor to force all references to the class to go through a static property.
Take a look at the System.Drawing.Color class. It uses this approach.
A: C# (the .NET framework in general, as far as I know) doesn't support parametrized enums like Java does. That being said, you might want to look at Attributes. Some of the features that Java enums are capable of are somewhat doable through Attributes.
A: What's wrong with just using a class for this? Its ugly, but thats how the Java people did it until they had language integrated Enum support!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When is a CDATA section necessary within a script tag? Are CDATA tags ever necessary in script tags and if so when?
In other words, when and where is this:
<script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>
preferable to this:
<script type="text/javascript">
...code...
</script>
A: When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.
A: to avoid xml errors during xhtml validation.
A: CDATA tells the browser to display the text as is and not to render it as an HTML.
A: A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) and you want to be able to write literal i<10 and a && b instead of i<10 and a && b, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will probably want to use a CDATA section.
Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.
For a good writeup on the subject, see https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm
A: CDATA is necessary in any XML dialect, because text within an XML node is treated as a child element before being evaluated as JavaScript. This is also the reason why JSLint complains about the < character in regexes.
References
*
*Creating a declarative XML UI language
*The Future of the Web: Rich Clients, Rich Browsers, Rich Portals
A: CDATA indicates that the contents within are not XML.
A: Basically it is to allow to write a document that is both XHTML and HTML. The problem is that within XHTML, the XML parser will interpret the &,<,> characters in the script tag and cause XML parsing error. So, you can write your JavaScript with entities, e.g.:
if (a > b) alert('hello world');
But this is impractical. The bigger problem is that if you read the page in HTML, the tag script is considered CDATA 'by default', and such JavaScript will not run. Therefore, if you want the same page to be OK both using XHTML and HTML parsers, you need to enclose the script tag in CDATA element in XHTML, but NOT to enclose it in HTML.
This trick marks the start of a CDATA element as a JavaScript comment; in HTML the JavaScript parser ignores the CDATA tag (it's a comment). In XHTML, the XML parser (which is run before the JavaScript) detects it and treats the rest until end of CDATA as CDATA.
A: It's an X(HT)ML thing. When you use symbols like < and > within the JavaScript, e.g. for comparing two integers, this would have to be parsed like XML, thus they would mark as a beginning or end of a tag.
The CDATA means that the following lines (everything up unto the ]]> is not XML and thus should not be parsed that way.
A: When browsers treat the markup as XML:
<script>
<![CDATA[
...code...
]]>
</script>
When browsers treat the markup as HTML:
<script>
...code...
</script>
When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate.
<script>
//<![CDATA[
...code...
//]]>
</script>
A: When you want it to validate (in XML/XHTML - thanks, Loren Segal).
A: That way older browser don't parse the Javascript code and the page doesn't break.
Backwards compatability. Gotta love it.
A: Do not use CDATA in HTML4 but you should use CDATA in XHTML and must use CDATA in XML if you have unescaped symbols like < and >.
A: It to ensure that XHTML validation works correctly when you have JavaScript embedded in your page, rather than externally referenced.
XHTML requires that your page strictly conform to XML markup requirements. Since JavaScript may contain characters with special meaning, you must wrap it in CDATA to ensure that validation does not flag it as malformed.
With HTML pages on the web you can just include the required JavaScript between and tags. When you validate the HTML on your web page the JavaScript content is considered to be CDATA (character data) that is therefore ignored by the validator. The same is not true if you follow the more recent XHTML standards in setting up your web page. With XHTML the code between the script tags is considered to be PCDATA (parsed character data) which is therefore processed by the validator.
Because of this, you can't just include JavaScript between the script tags on your page without 'breaking' your web page (at least as far as the validator is concerned).
You can learn more about CDATA here, and more about XHTML here.
A: HTML
An HTML parser will treat everything between <script> and </script> as part of the script. Some implementations don't even need a correct closing tag; they stop script interpretation at "</", which is correct according to the specs.
Update In HTML5, and with current browsers, that is not the case anymore.
So, in HTML, this is not possible:
<script>
var x = '</script>';
alert(x)
</script>
A CDATA section has no effect at all. That's why you need to write
var x = '<' + '/script>'; // or
var x = '<\/script>';
or similar.
This also applies to XHTML files served as text/html. (Since IE does not support XML content types, this is mostly true.)
XML
In XML, different rules apply. Note that (non IE) browsers only use an XML parser if the XHMTL document is served with an XML content type.
To the XML parser, a script tag is no better than any other tag. Particularly, a script node may contain non-text child nodes, triggered by "<"; and a "&" sign denotes a character entity.
So, in XHTML, this is not possible:
<script>
if (a<b && c<d) {
alert('Hooray');
}
</script>
To work around this, you can wrap the whole script in a CDATA section. This tells the parser: 'In this section, don't treat "<" and "&" as control characters.' To prevent the JavaScript engine from interpreting the "<![CDATA[" and "]]>" marks, you can wrap them in comments.
If your script does not contain any "<" or "&", you don't need a CDATA section anyway.
A: CDATA indicates that the contents within are not XML.
Here is an explanation on wikipedia
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "961"
} |
Q: Integration of JavaScript and JMS Where can I find a guide for integrating JavaScript and JMS (Java Messaging Service)?
I would like a best practice or established technology that allows me to directly or indirectly receive messages from a topic and update a site based on the message. I was thinking of creating two components, a servlet for the Web module, and an MDB (Message-Driven Bean) for the EJB module. The web client will comsume messages from the JMS topic, and the MDB will handle the onMessage.
Does this sound correct? Have you seen any examples?
Edit: I am using ActiveMQ for the JMS.
A: I think this is your answer. Looks like it is baked in to ActiveMQ. I tried the examples and they seem to work.
http://activemq.apache.org/ajax.html
A: I would try using DWR to integrate JavaScript with your Java app. It makes Java to JavaScript communication transparent and only requires one servlet + configuration of what to expose. I haven´t done this with JMS, but it should work the same. There are three technologies that together solve all my integration problems, Spring, Mule, and DWR.
A: You'll find some references to the Dojo/Bayeux approach here
http://www.pathf.com/blogs/2006/08/bayeux_a_json_p/
If you're using WebSphere 6.0 or higher then the Web 2.0 Feature Pack includes an implementation.
A: The Seam framework supports subscription to JMS topics from a JavaScript based client:
http://docs.jboss.com/seam/2.0.2.GA/reference/en-US/html/remoting.html#d0e14169
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I run a program as nobody? I want a user-privileged (not root) process to launch new processes as user nobody. I've tried a straight call to setuid that fails with -1 EPERM on Ubuntu 8.04:
#include <sys/types.h>
#include <unistd.h>
int main() {
setuid(65534);
while (1);
return 0;
}
How should I do this instead?
A: You will require assistance and a lot of trust from your system administrator. Ordinary users are not able to run the executable of their choice on behalf on other users, period.
She may add your application to /etc/sudoers with proper settings and you'll be able to run it as with sudo -u nobody. This will work for both scripts and binary executables.
Another option is that she will do chown nobody and chmod +s on your binary executable and you'll be able to execute it directly. This task must be repeated each time your executable changes.
This could also work for scripts if you'll create a tiny helper executable which simply does exec("/home/you/bin/your-application"). This executable can be made suid-nobody (see above) and you may freely modify your-application.
A: As far as I know, you can't unless you're root or have sudo set up to allow you to switch users. Or, you can have your executable have the suid bit set up on it, and have it owned by nobody. But that requires root access too.
A: calife is an alternative to sudo.
Calife is small program that enable a UNIX system administrator to become root (or another user) on his/her machines without giving the root password but his/her own.
A: The 'nobody' user is still a user. I'm not sure what your reasoning is in having the program run as nobody, it's not going to be adding any additional security. You're more likely to open yourself to other problems.
I'd follow squadette's recommendation of using a helper application.
A: I ran across the setuid-sandbox project today while reading LWN, which does what I'm looking for the proper way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Java applet cached forever, not downloading new version? We have a case where clients seem to be eternally caching versions of applets. We're making use of the <param name="cache_version"> tag correctly within our <object> tag, or so we think. We went from a version string of 7.1.0.40 to 7.1.0.42 and this triggered a download for only about half of our clients.
It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6.
Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the cache_archive's "Last-Modified" and/or "Content-Length" values (as per Sun's Site)?
FYI, object block looks like this:
<object>
<param name="ARCHIVE" value="foo.jar">
<param name="CODE" value="com.foo.class">
<param name="CODEBASE" value=".">
<param name="cache_archive" value="foo.jar">
<param name="cache_version" value="7.1.0.40">
<param name="NAME" value="FooApplet">
<param name="type" value="application/x-java-applet;jpi-version=1.4.2_13">
<param name="scriptable" value="true">
<param name="progressbar" value="true"/>
<param name="boxmessage" value="Loading Web Worksheet Applet..."/>
</object>
A: Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under the most recent versions of the JRE.
The only solution GUARANTEED to work is to rename your application jars when their versions change (we've seen strange caching behavior when trying other tricks like adding query strings based on file dates). This isn't so difficult to do if you have a properly automated deployment system.
A: You can remove applet from Java cache using Java Control Panel.
For example, on Win XP
Start -> Control Panel -> Java -> Temporary Internet Files[View]
A: As per this link
, same jar file should not be listed int "archive" and "cache_archive" params. In that case, the JAR file is cached using the native browser cache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to test credit card interactions? After reading this answer, I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.
A: MasterCard: 5431111111111111
Amex: 341111111111111
Discover: 6011601160116611
American Express (15 digits) 378282246310005
American Express (15 digits) 371449635398431
American Express Corporate (15 digits) 378734493671000
Diners Club (14 digits) 30569309025904
Diners Club (14 digits) 38520000023237
Discover (16 digits) 6011111111111117
Discover (16 digits) 6011000990139424
JCB (16 digits) 3530111333300000
JCB (16 digits) 3566002020360505
MasterCard (16 digits) 5555555555554444
MasterCard (16 digits) 5105105105105100
Visa (16 digits) 4111111111111111
Visa (16 digits) 4012888888881881
Visa (13 digits) 4222222222222
Credit Card Prefix Numbers:
Visa: 13 or 16 numbers starting with 4
MasterCard: 16 numbers starting with 5
Discover: 16 numbers starting with 6011
AMEX: 15 numbers starting with 34 or 37
A: Most payment gateways provide such numbers for testing their services, but they will generally only work on the staging/test versions of those gateways.
A: Depending on your payment gateway, there are two ways to test a transaction.
For example, with authorize.net, if you send "X_TEST_TRANSACTION=true" (or something like that, its been a long time), with your POST, it will run it in test mode.
They also provide a test VISA and test Mastercard number that will always come back as approved if in test mode, and declined in production mode.
Look at your gateway API documentation, it will be clearly detailed there.
A: Most payment processors provide either a testing number (PayPal does this) or the ability to go into testing mode (in which no transactions actually get processed). Consult the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Simplest way to check if two integers have same sign? Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?
A: Assuming 32 bit ints:
bool same = ((x ^ y) >> 31) != 1;
Slightly more terse:
bool same = !((x ^ y) >> 31);
A: Here is a version that works in C/C++ that doesn't rely on integer sizes or have the overflow problem (i.e. x*y>=0 doesn't work)
bool SameSign(int x, int y)
{
return (x >= 0) ^ (y < 0);
}
Of course, you can geek out and template:
template <typename valueType>
bool SameSign(typename valueType x, typename valueType y)
{
return (x >= 0) ^ (y < 0);
}
Note: Since we are using exclusive or, we want the LHS and the RHS to be different when the signs are the same, thus the different check against zero.
A: (integer1 * integer2) > 0
Because when two integers share a sign, the result of multiplication will always be positive.
You can also make it >= 0 if you want to treat 0 as being the same sign no matter what.
A: I'm not really sure I'd consider "bitwise trick" and "simplest" to be synonymous. I see a lot of answers that are assuming signed 32-bit integers (though it would be silly to ask for unsigned); I'm not certain they'd apply to floating-point values.
It seems like the "simplest" check would be to compare how both values compare to 0; this is pretty generic assuming the types can be compared:
bool compare(T left, T right)
{
return (left < 0) == (right < 0);
}
If the signs are opposite, you get false. If the signs are the same, you get true.
A: Assuming twos complement arithmetic (http://en.wikipedia.org/wiki/Two_complement):
inline bool same_sign(int x, int y) {
return (x^y) >= 0;
}
This can take as little as two instructions and less than 1ns on a modern processor with optimization.
Not assuming twos complement arithmetic:
inline bool same_sign(int x, int y) {
return (x<0) == (y<0);
}
This may require one or two extra instructions and take a little longer.
Using multiplication is a bad idea because it is vulnerable to overflow.
A: (a ^ b) >= 0
will evaluate to 1 if the sign is the same, 0 otherwise.
A: if (x * y) > 0...
assuming non-zero and such.
A: What's wrong with
return ((x<0) == (y<0));
?
A: As a technical note, bit-twiddly solutions are going to be much more efficient than multiplication, even on modern architectures. It's only about 3 cycles that you're saving, but you know what they say about a "penny saved"...
A: I would be wary of any bitwise tricks to determine the sign of integers, as then you have to make assumptions about how those numbers are represented internally.
Almost 100% of the time, integers will be stored as two's compliment, but it's not good practice to make assumptions about the internals of a system unless you are using a datatype that guarentees a particular storage format.
In two's compliment, you can just check the last (left-most) bit in the integer to determine if it is negative, so you can compare just these two bits. This would mean that 0 would have the same sign as a positive number though, which is at odds with the sign function implemented in most languages.
Personally, I'd just use the sign function of your chosen language. It is unlikely that there would be any performance issues with a calculation such as this.
A: Just off the top of my head...
int mask = 1 << 31;
(a & mask) ^ (b & mask) < 0;
A: if (a*b < 0) sign is different, else sign is the same (or a or b is zero)
A: For any size of int with two's complement arithmetic:
#define SIGNBIT (~((unsigned int)-1 >> 1))
if ((x & SIGNBIT) == (y & SIGNBIT))
// signs are the same
A: assuming 32 bit
if(((x^y) & 0x80000000) == 0)
... the answer if(x*y>0) is bad due to overflow
A: branchless C version:
int sameSign(int a, int b) {
return ~(a^b) & (1<<(sizeof(int)*8-1));
}
C++ template for integer types:
template <typename T> T sameSign(T a, T b) {
return ~(a^b) & (1<<(sizeof(T)*8-1));
}
A: Thinking back to my university days, in most machine representations, isn't the left-most bit of a integer a 1 when the number is negative, and 0 when it's positive?
I imagine this is rather machine-dependent, though.
A: int same_sign = !( (x >> 31) ^ (y >> 31) );
if ( same_sign ) ...
else ...
A: Better way using std::signbit as follows:
std::signbit(firstNumber) == std::signbit(secondNumber);
It also support other basic types (double, float, char etc).
A: #include<stdio.h>
int checksign(int a, int b)
{
return (a ^ b);
}
void main()
{
int a=-1, b = 0;
if(checksign(a,b)<0)
{
printf("Integers have the opposite sign");
}
else
{
printf("Integers have the same sign");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
} |
Q: OpenID support for Ruby on Rails application What is current state of the art for enabling OpenID login in Ruby on Rails applications? This is a community wiki with up-to-date answers to this question.
Authlogic
The most advanced authentication solution seems to be Authlogic. It supports OpenID with Authlogic OpenID plugin. It supports Rails 4 and 3. Rails 2 is supported in the rails2 branch.
You may want to watch "OpenID with Authlogic" railscast (and the "Authlogic" railscast).
There is a sample application called Authlogic OpenID Selector Example.
Devise
Devise is flexible authentication framework for Rails. It supports OpenID with devise_openid_authenticatable.
restful_authentication
Another authentication library of choice is restful_authentication Rails plugin. Seems like you also need to install open_id_authentication plugin.
You may want to watch (old, circa 2007) "OpenID Authentication" railscast.
Ruby OpenID
Raw support for OpenID protocol is handled by Ruby OpenID library.
A: Check out this Railscast on OpenId for more info. I'm not sure if/how it might work alongside restful_authentication, but might be a good resource. (I haven't watched it yet)
A: What I've done is use restful-authentication and then blend the open_id_authentication plugin into your application. It might help to setup the open_id_authentication plugin on a test app as well, so you can determine the changes you'll need to make to the users table.
A: The definitive resource should be the rails wiki, although I use should advisedly because things have been changing quite fast when it comes to OpenID support.
Ryan Bates' Railscast on Openid is the best thing I've found to follow. Even though it was recorded with Rails 1.2.3, I've been able to successfully follow the tutorial with Rails 2.1.0. The only point to note is that for:
gem install ruby-openid
I installed 2.1.2, rather than the 1.1.4 used in railscast.
The OpenID plugin used is open_id_authentication, and I tested it in combination with restful_authentication from git://github.com/technoweenie/restful-authentication.git
NB: I subsequently wrote this up in a blog post.
A: The only gem I know of that supports OpenID Connect (the latest version) is:
https://github.com/nov/openid_connect
However, it has absolutely no documentation. :(
A: Bort now has OpenID included, in addition to restful_authentication.
A: Oddly, this subject doesn't appear to have received much attention from the Rails community since 2007.
The latest trunk of Bort didn't seem to work with Rails 2.3.x, so I forked it and got it working.
I also added some things that I personally use - like yui reset/base, jquery, etc.
The fork is very much still a work in progress, but I hope to provide broad, tested authentication support for restful auth, google auth, facebook connect, twitter, etc.
http://github.com/lukebayes/bort
A: I have found that using BinaryLogic's Authlogic gems are quite easy and straightforward to use. See Authlogic and its OpenID plugin.
You can download an example application or try it!
A: Keep an eye on Bort. It is a base rails application which already has restful_authentication setup among other things. The guy doing it is planning on adding OpenID.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Tree data structure in C# I was looking for a tree or graph data structure in C#, but I guess there isn't one provided. An Extensive Examination of Data Structures Using C# 2.0 a bit about why. Is there a convenient library which is commonly used to provide this functionality? Perhaps through a strategy pattern to solve the issues presented in the article.
I feel a bit silly implementing my own tree, just as I would implementing my own ArrayList.
I just want a generic tree which can be unbalanced. Think of a directory tree. C5 looks nifty, but their tree structures seem to be implemented as balanced red-black trees better suited to search than representing a hierarchy of nodes.
A: I have a little extension to the solutions.
Using a recursive generic declaration and a deriving subclass, you can better concentrate on your actual target.
Notice, it’s different from a non generic implementation, you don’t need to cast 'node' to 'NodeWorker'.
Here's my example:
public class GenericTree<T> where T : GenericTree<T> // recursive constraint
{
// no specific data declaration
protected List<T> children;
public GenericTree()
{
this.children = new List<T>();
}
public virtual void AddChild(T newChild)
{
this.children.Add(newChild);
}
public void Traverse(Action<int, T> visitor)
{
this.traverse(0, visitor);
}
protected virtual void traverse(int depth, Action<int, T> visitor)
{
visitor(depth, (T)this);
foreach (T child in this.children)
child.traverse(depth + 1, visitor);
}
}
public class GenericTreeNext : GenericTree<GenericTreeNext> // concrete derivation
{
public string Name {get; set;} // user-data example
public GenericTreeNext(string name)
{
this.Name = name;
}
}
static void Main(string[] args)
{
GenericTreeNext tree = new GenericTreeNext("Main-Harry");
tree.AddChild(new GenericTreeNext("Main-Sub-Willy"));
GenericTreeNext inter = new GenericTreeNext("Main-Inter-Willy");
inter.AddChild(new GenericTreeNext("Inter-Sub-Tom"));
inter.AddChild(new GenericTreeNext("Inter-Sub-Magda"));
tree.AddChild(inter);
tree.AddChild(new GenericTreeNext("Main-Sub-Chantal"));
tree.Traverse(NodeWorker);
}
static void NodeWorker(int depth, GenericTreeNext node)
{ // a little one-line string-concatenation (n-times)
Console.WriteLine("{0}{1}: {2}", String.Join(" ", new string[depth + 1]), depth, node.Name);
}
A: Here's mine, which is very similar to Aaron Gage's, just a little more conventional, in my opinion. For my purposes, I haven't ran into any performance issues with List<T>. It would be easy enough to switch to a LinkedList if needed.
namespace Overby.Collections
{
public class TreeNode<T>
{
private readonly T _value;
private readonly List<TreeNode<T>> _children = new List<TreeNode<T>>();
public TreeNode(T value)
{
_value = value;
}
public TreeNode<T> this[int i]
{
get { return _children[i]; }
}
public TreeNode<T> Parent { get; private set; }
public T Value { get { return _value; } }
public ReadOnlyCollection<TreeNode<T>> Children
{
get { return _children.AsReadOnly(); }
}
public TreeNode<T> AddChild(T value)
{
var node = new TreeNode<T>(value) {Parent = this};
_children.Add(node);
return node;
}
public TreeNode<T>[] AddChildren(params T[] values)
{
return values.Select(AddChild).ToArray();
}
public bool RemoveChild(TreeNode<T> node)
{
return _children.Remove(node);
}
public void Traverse(Action<T> action)
{
action(Value);
foreach (var child in _children)
child.Traverse(action);
}
public IEnumerable<T> Flatten()
{
return new[] {Value}.Concat(_children.SelectMany(x => x.Flatten()));
}
}
}
A: Yet another tree structure:
public class TreeNode<T> : IEnumerable<TreeNode<T>>
{
public T Data { get; set; }
public TreeNode<T> Parent { get; set; }
public ICollection<TreeNode<T>> Children { get; set; }
public TreeNode(T data)
{
this.Data = data;
this.Children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> AddChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
this.Children.Add(childNode);
return childNode;
}
... // for iterator details see below link
}
Sample usage:
TreeNode<string> root = new TreeNode<string>("root");
{
TreeNode<string> node0 = root.AddChild("node0");
TreeNode<string> node1 = root.AddChild("node1");
TreeNode<string> node2 = root.AddChild("node2");
{
TreeNode<string> node20 = node2.AddChild(null);
TreeNode<string> node21 = node2.AddChild("node21");
{
TreeNode<string> node210 = node21.AddChild("node210");
TreeNode<string> node211 = node21.AddChild("node211");
}
}
TreeNode<string> node3 = root.AddChild("node3");
{
TreeNode<string> node30 = node3.AddChild("node30");
}
}
BONUS
See fully-fledged tree with:
*
*iterator
*searching
*Java/C#
https://github.com/gt4dev/yet-another-tree-structure
A: Try this simple sample.
public class TreeNode<TValue>
{
#region Properties
public TValue Value { get; set; }
public List<TreeNode<TValue>> Children { get; private set; }
public bool HasChild { get { return Children.Any(); } }
#endregion
#region Constructor
public TreeNode()
{
this.Children = new List<TreeNode<TValue>>();
}
public TreeNode(TValue value)
: this()
{
this.Value = value;
}
#endregion
#region Methods
public void AddChild(TreeNode<TValue> treeNode)
{
Children.Add(treeNode);
}
public void AddChild(TValue value)
{
var treeNode = new TreeNode<TValue>(value);
AddChild(treeNode);
}
#endregion
}
A: I created a Node<T> class that could be helpful for other people. The class has properties like:
*
*Children
*Ancestors
*Descendants
*Siblings
*Level of the node
*Parent
*Root
*Etc.
There is also the possibility to convert a flat list of items with an Id and a ParentId to a tree. The nodes holds a reference to both the children and the parent, so that makes iterating nodes quite fast.
A: The generally excellent C5 Generic Collection Library has several different tree-based data structures, including sets, bags and dictionaries. Source code is available if you want to study their implementation details. (I have used C5 collections in production code with good results, although I haven't used any of the tree structures specifically.)
A: There is the now released .NET codebase: specifically the code for a SortedSet that implements a red-black tree: sortedset.cs
This is, however, a balanced tree structure. So my answer is more a reference to what I believe is the only native tree-structure in the .NET core library.
A: I've completed the code that Berezh has shared.
public class TreeNode<T> : IEnumerable<TreeNode<T>>
{
public T Data { get; set; }
public TreeNode<T> Parent { get; set; }
public ICollection<TreeNode<T>> Children { get; set; }
public TreeNode(T data)
{
this.Data = data;
this.Children = new LinkedList<TreeNode<T>>();
}
public TreeNode<T> AddChild(T child)
{
TreeNode<T> childNode = new TreeNode<T>(child) { Parent = this };
this.Children.Add(childNode);
return childNode;
}
public IEnumerator<TreeNode<T>> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
}
public class TreeNodeEnum<T> : IEnumerator<TreeNode<T>>
{
int position = -1;
public List<TreeNode<T>> Nodes { get; set; }
public TreeNode<T> Current
{
get
{
try
{
return Nodes[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public TreeNodeEnum(List<TreeNode<T>> nodes)
{
Nodes = nodes;
}
public void Dispose()
{
}
public bool MoveNext()
{
position++;
return (position < Nodes.Count);
}
public void Reset()
{
position = -1;
}
}
A: I have added a complete solution and example using the NTree class above. I also added the "AddChild" method...
public class NTree<T>
{
public T data;
public LinkedList<NTree<T>> children;
public NTree(T data)
{
this.data = data;
children = new LinkedList<NTree<T>>();
}
public void AddChild(T data)
{
var node = new NTree<T>(data) { Parent = this };
children.AddFirst(node);
}
public NTree<T> Parent { get; private set; }
public NTree<T> GetChild(int i)
{
foreach (NTree<T> n in children)
if (--i == 0)
return n;
return null;
}
public void Traverse(NTree<T> node, TreeVisitor<T> visitor, string t, ref NTree<T> r)
{
visitor(node.data, node, t, ref r);
foreach (NTree<T> kid in node.children)
Traverse(kid, visitor, t, ref r);
}
}
public static void DelegateMethod(KeyValuePair<string, string> data, NTree<KeyValuePair<string, string>> node, string t, ref NTree<KeyValuePair<string, string>> r)
{
string a = string.Empty;
if (node.data.Key == t)
{
r = node;
return;
}
}
Using it
NTree<KeyValuePair<string, string>> ret = null;
tree.Traverse(tree, DelegateMethod, node["categoryId"].InnerText, ref ret);
A: There is also the possibility to use XML with LINQ:
Create XML tree in C# (LINQ to XML)
XML is the most mature and flexible solution when it comes to using trees and LINQ provides you with all the tools that you need.
The configuration of your tree also gets much cleaner and user-friendly as you can simply use an XML file for the initialization.
If you need to work with objects, you can use XML serialization:
XML serialization
A: My best advice would be that there is no standard tree data structure because there are so many ways you could implement it that it would be impossible to cover all bases with one solution. The more specific a solution, the less likely it is applicable to any given problem. I even get annoyed with LinkedList - what if I want a circular linked list?
The basic structure you'll need to implement will be a collection of nodes, and here are some options to get you started. Let's assume that the class Node is the base class of the entire solution.
If you need to only navigate down the tree, then a Node class needs a List of children.
If you need to navigate up the tree, then the Node class needs a link to its parent node.
Build an AddChild method that takes care of all the minutia of these two points and any other business logic that must be implemented (child limits, sorting the children, etc.)
A: delegate void TreeVisitor<T>(T nodeData);
class NTree<T>
{
private T data;
private LinkedList<NTree<T>> children;
public NTree(T data)
{
this.data = data;
children = new LinkedList<NTree<T>>();
}
public void AddChild(T data)
{
children.AddFirst(new NTree<T>(data));
}
public NTree<T> GetChild(int i)
{
foreach (NTree<T> n in children)
if (--i == 0)
return n;
return null;
}
public void Traverse(NTree<T> node, TreeVisitor<T> visitor)
{
visitor(node.data);
foreach (NTree<T> kid in node.children)
Traverse(kid, visitor);
}
}
Simple recursive implementation...
< 40 lines of code...
You just need to keep a reference to the root of the tree outside of the class,
or wrap it in another class, maybe rename to TreeNode??
A: See https://github.com/YaccConstructor/QuickGraph (previously http://quickgraph.codeplex.com/)
QuickGraph provides generic directed/undirected graph data structures and algorithms for .NET 2.0 and up. QuickGraph comes with algorithms such as depth-first search, breadth-first search, A* search, shortest path, k-shortest path, maximum flow, minimum spanning tree, least common ancestors, etc... QuickGraph supports MSAGL, GLEE, and Graphviz to render the graphs, serialization to GraphML, etc.
A: Here's my own:
class Program
{
static void Main(string[] args)
{
var tree = new Tree<string>()
.Begin("Fastfood")
.Begin("Pizza")
.Add("Margherita")
.Add("Marinara")
.End()
.Begin("Burger")
.Add("Cheese burger")
.Add("Chili burger")
.Add("Rice burger")
.End()
.End();
tree.Nodes.ForEach(p => PrintNode(p, 0));
Console.ReadKey();
}
static void PrintNode<T>(TreeNode<T> node, int level)
{
Console.WriteLine("{0}{1}", new string(' ', level * 3), node.Value);
level++;
node.Children.ForEach(p => PrintNode(p, level));
}
}
public class Tree<T>
{
private Stack<TreeNode<T>> m_Stack = new Stack<TreeNode<T>>();
public List<TreeNode<T>> Nodes { get; } = new List<TreeNode<T>>();
public Tree<T> Begin(T val)
{
if (m_Stack.Count == 0)
{
var node = new TreeNode<T>(val, null);
Nodes.Add(node);
m_Stack.Push(node);
}
else
{
var node = m_Stack.Peek().Add(val);
m_Stack.Push(node);
}
return this;
}
public Tree<T> Add(T val)
{
m_Stack.Peek().Add(val);
return this;
}
public Tree<T> End()
{
m_Stack.Pop();
return this;
}
}
public class TreeNode<T>
{
public T Value { get; }
public TreeNode<T> Parent { get; }
public List<TreeNode<T>> Children { get; }
public TreeNode(T val, TreeNode<T> parent)
{
Value = val;
Parent = parent;
Children = new List<TreeNode<T>>();
}
public TreeNode<T> Add(T val)
{
var node = new TreeNode<T>(val, this);
Children.Add(node);
return node;
}
}
Output:
Fastfood
Pizza
Margherita
Marinara
Burger
Cheese burger
Chili burger
Rice burger
A: Most trees are formed by the data you are processing.
Say you have a person class that includes details of someone’s
parents, would you rather have the tree structure as part of your
“domain class”, or use a separate tree class that contained links to
your person objects? Think about a simple operation like getting all
the grandchildren of a person, should this code be in the person
class, or should the user of the person class have to know about a
separate tree class?
Another example is a parse tree in a compiler…
Both of these examples show that the concept of a tree is part of the domain of the data and using a separate general-purpose tree at least doubles the number of objects that are created as well as making the API harder to program again.
We want a way to reuse the standard tree operations, without having to reimplement them for all trees, while at the same time, not having to use a standard tree class. Boost has tried to solve this type of problem for C++, but I am yet to see any effect for .NET to get it adapted.
A: Here is my implementation of a BST:
class BST
{
public class Node
{
public Node Left { get; set; }
public object Data { get; set; }
public Node Right { get; set; }
public Node()
{
Data = null;
}
public Node(int Data)
{
this.Data = (object)Data;
}
public void Insert(int Data)
{
if (this.Data == null)
{
this.Data = (object)Data;
return;
}
if (Data > (int)this.Data)
{
if (this.Right == null)
{
this.Right = new Node(Data);
}
else
{
this.Right.Insert(Data);
}
}
if (Data <= (int)this.Data)
{
if (this.Left == null)
{
this.Left = new Node(Data);
}
else
{
this.Left.Insert(Data);
}
}
}
public void TraverseInOrder()
{
if(this.Left != null)
this.Left.TraverseInOrder();
Console.Write("{0} ", this.Data);
if (this.Right != null)
this.Right.TraverseInOrder();
}
}
public Node Root { get; set; }
public BST()
{
Root = new Node();
}
}
A: If you are going to display this tree on the GUI, you can use TreeView and TreeNode. (I suppose technically you can create a TreeNode without putting it on a GUI, but it does have more overhead than a simple homegrown TreeNode implementation.)
A: In case you need a rooted tree data structure implementation that uses less memory, you can write your Node class as follows (C++ implementation):
class Node {
Node* parent;
int item; // depending on your needs
Node* firstChild; //pointer to left most child of node
Node* nextSibling; //pointer to the sibling to the right
}
A: Tree With Generic Data
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class Tree<T>
{
public T Data { get; set; }
public LinkedList<Tree<T>> Children { get; set; } = new LinkedList<Tree<T>>();
public Task Traverse(Func<T, Task> actionOnNode, int maxDegreeOfParallelism = 1) => Traverse(actionOnNode, new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism));
private async Task Traverse(Func<T, Task> actionOnNode, SemaphoreSlim semaphore)
{
await actionOnNode(Data);
SafeRelease(semaphore);
IEnumerable<Task> tasks = Children.Select(async input =>
{
await semaphore.WaitAsync().ConfigureAwait(false);
try
{
await input.Traverse(actionOnNode, semaphore).ConfigureAwait(false);
}
finally
{
SafeRelease(semaphore);
}
});
await Task.WhenAll(tasks);
}
private void SafeRelease(SemaphoreSlim semaphore)
{
try
{
semaphore.Release();
}
catch (Exception ex)
{
if (ex.Message.ToLower() != "Adding the specified count to the semaphore would cause it to exceed its maximum count.".ToLower())
{
throw;
}
}
}
public async Task<IEnumerable<T>> ToList()
{
ConcurrentBag<T> lst = new ConcurrentBag<T>();
await Traverse(async (data) => lst.Add(data));
return lst;
}
public async Task<int> Count() => (await ToList()).Count();
}
Unit Tests
using System.Threading.Tasks;
using Xunit;
public class Tree_Tests
{
[Fact]
public async Task Tree_ToList_Count()
{
Tree<int> head = new Tree<int>();
Assert.NotEmpty(await head.ToList());
Assert.True(await head.Count() == 1);
// child
var child = new Tree<int>();
head.Children.AddFirst(child);
Assert.True(await head.Count() == 2);
Assert.NotEmpty(await head.ToList());
// grandson
child.Children.AddFirst(new Tree<int>());
child.Children.AddFirst(new Tree<int>());
Assert.True(await head.Count() == 4);
Assert.NotEmpty(await head.ToList());
}
[Fact]
public async Task Tree_Traverse()
{
Tree<int> head = new Tree<int>() { Data = 1 };
// child
var child = new Tree<int>() { Data = 2 };
head.Children.AddFirst(child);
// grandson
child.Children.AddFirst(new Tree<int>() { Data = 3 });
child.Children.AddLast(new Tree<int>() { Data = 4 });
int counter = 0;
await head.Traverse(async (data) => counter += data);
Assert.True(counter == 10);
counter = 0;
await child.Traverse(async (data) => counter += data);
Assert.True(counter == 9);
counter = 0;
await child.Children.First!.Value.Traverse(async (data) => counter += data);
Assert.True(counter == 3);
counter = 0;
await child.Children.Last!.Value.Traverse(async (data) => counter += data);
Assert.True(counter == 4);
}
}
A: I don't like a tree aproach. It gets things overcomplicated including search or dril-down or even ui controls populating.
I would suggest to use a very simple approach with IDictionary<TChild, TParent>. This also allows to have no connections between nodes or levels.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "286"
} |
Q: Virtualizing treelistview? Does anyone know of a good way to display hierarchical data with columns?
It has to be virtualizing, as it must be able to handle several million records.
It should also be multi-select, most treeview controls are not.
Winforms preferred, but will ElementHost WPF if necessary.
A: I'm not quite clear what you mean about hierarchical data with columns, can you clarify? One possibility is the new WPF DataGrid. Depending on the functionality you're looking for it may be what you're looking for.
The bits for datagrid are available on codeplex:
http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14963
A: Take a look at the Infragistics UltraWinGrid, here's a video that demos some features:
http://www.infragistics.com/howto/wingrid.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: The doesn't display properly when using inside In a JSP page, I created a <h:form enctype="multipart/form-data"> with some elements: <t:inputText>, <t:inputDate>, etc. Also, I added some <t:message for="someElement"> And I wanted to allow the user upload several files (one at a time) within the form (using <t:inputFileUpload> ) At this point my code works fine.
The headache comes when I try to put the form inside a <t:panelTabbedPane serverSideTabSwitch="false"> (and thus of course, inside a <t:panelTab> )
I copied the structure shown in the source code for TabbedPane example from Tomahawk's examples, by using the <f:subview> tag and putting the panelTab tag inside a new jsp page (using <jsp:include page="somePage.jsp"> directive)
First at all, the <t:inputFileUpload> fails to load the file at the value assigned in the Managed Bean UploadedFile attribute #{myBean.upFile}
Then, googling for a clue, I knew that <t:panelTabbedPane> generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the <h:form> out of the <t:panelTabbedPane> and eureka! file input worked again! (the autoform doesn't generate)
But, oh surprise! oh terrible Murphy law! All my <h:message> begins to fail. The Eclipse console's output show me that all <t:message> are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change)
At this point, I put a <t:mesagges> tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel.
All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined.
¿How can I get the <t:message for="xyz"> working properly?
I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application)
"SOLVED": This problem is an issue reported to myFaces forum.
Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!)
See the issue
EDIT 1
1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the <t:message for="xyz"> tags work.
What I did was:
1. Having my tag <inputText id="name" forceId="true" required="true"> The <t:message> doesn't work.
2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: <inputText id="namej_id_1" forceId="true" required="true">
3. Then the <t:message> worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle)
4. This implies that the user have to press 2 times the submit button to get the error messages on the page.
5. And using the "j_id_1" phrase at the end of IDs is very weird.
EDIT 2
Ok, here comes the code, hope it not be annoying.
1.- mainPage.jsp (here is the <t:panelTabbedPane> and <f:subview> tags)
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%>
<html>
<body>
<f:view>
<h:form enctype="multipart/form-data">
<t:panelTabbedPane serverSideTabSwitch="false" >
<f:subview id="subview_tab_detail">
<jsp:include page="detail.jsp"/>
</f:subview>
</t:panelTabbedPane>
</h:form>
</f:view>
</body>
</html>
2.- detail.jsp (here is the <t:panelTab> tag)
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%>
<t:panelTab label="TAB_1">
<t:panelGrid columns="3">
<f:facet name="header">
<h:outputText value="CREATING A TICKET" />
</f:facet>
<t:outputLabel for="ticket_id" value="TICKET ID" />
<t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" />
<t:message for="ticket_id" />
<t:outputLabel for="description" value="DESCRIPTION" />
<t:inputText id="description" value="#{myBean.ticketDescription}" required="true" />
<t:message for="description" />
<t:outputLabel for="attachment" value="ATTACHMENTS" />
<t:panelGroup>
<!-- This is for listing multiple file uploads -->
<!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) -->
<t:panelGrid columns="3" binding="#{myBean.panelUpload}" />
<t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" />
<t:commandButton value="ADD FILE" action="#{myBean.upload}" />
</t:panelGroup>
<t:message for="attachment" />
<t:commandButton action="#{myBean.create}" value="CREATE TICKET" />
</t:panelGrid>
</t:panelTab>
EDIT 3
On response to Kyle Renfro follow-up:
Kyle says:
"At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not."
Here is the behavior found:
1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up.
2.- The eclipse console shows me these internal errors:
ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid.
ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid.
ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid.
Here is when I saw the "j_id_1" word at the generated IDs, for example, for the id "ticket_id":
j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1
And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute):
<input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1">
A: The forceId attribute of the tomahawk components should solve this problem.
something like:
<t:outputText id="xyz" forceId="true" value="#{mybean.stuff}"/>
At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not.
A: Looks like it may be related a bug in myfaces. There is a newer version of myfaces and tomahawk that you might try. I would remove the subview functionality as a quick test - copy the detail.jsp page back into the main page.
https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to increment in vim under windows (where CTRL-A does not work...) While CtrlX works fine in vim under windows, CtrlA selects all (duh).
Is there a way to increment a number with a keystroke under windows?
A: You can make CtrlA to increment in windows by opening up the 'mswin.vim' file in your vim directory and finding the section that looks like:
" CTRL-A is Select all
noremap <C-A> gggH<C-O>G
inoremap <C-A> <C-O>gg<C-O>gH<C-O>G
cnoremap <C-A> <C-C>gggH<C-O>G
onoremap <C-A> <C-C>gggH<C-O>G
snoremap <C-A> <C-C>gggH<C-O>G
xnoremap <C-A> <C-C>ggVG
Comment out all of these lines as follows:
" CTRL-A is Select all
"noremap <C-A> gggH<C-O>G
"inoremap <C-A> <C-O>gg<C-O>gH<C-O>G
"cnoremap <C-A> <C-C>gggH<C-O>G
"onoremap <C-A> <C-C>gggH<C-O>G
"snoremap <C-A> <C-C>gggH<C-O>G
"xnoremap <C-A> <C-C>ggVG
and the CtrlA keystroke will increment.
This is a pretty nice option when your keyboard doesn't have a real number pad.
A: Try Ctrl-NumPad + ?
(from here)
A: I realize that this is an old question, but I ran across another option today based on the following question. Making gvim act like it does on linux will allow CTRL-A to work as you expect it to:
how to make gvim on windows behave exacly like linux console vim?
There is a section of the _vimrc that has the following items. These cause many of the control characters to act like they do on Windows.
set nocompatible
source $VIMRUNTIME/vimrc_example.vim
source $VIMRUNTIME/mswin.vim
behave mswin
I commented out (with ") the mswin lines and the set nocompatible line. From there, I added set compatible. This causes gvim to act like it does on linux. Thus, mine looks something like:
set compatible
source $VIMRUNTIME/vimrc_example.vim
"set nocompatible
"source $VIMRUNTIME/mswin.vim
"behave mswin
I just learned this trick today, so if I'm not completely correct in my information, please let me know.
A: I modified TMealy's solution so that CtrlA still selects all (I find this useful), while CtrlI increments (also useful).
noremap <C-I> <C-A>
" CTRL-A is Select all
noremap <C-A> gggH<C-O>G
inoremap <C-A> <C-O>gg<C-O>gH<C-O>G
cnoremap <C-A> <C-C>gggH<C-O>G
onoremap <C-A> <C-C>gggH<C-O>G
snoremap <C-A> <C-C>gggH<C-O>G
xnoremap <C-A> <C-C>ggVG
A: A similar problem occurs under GNU/Linux when using Vim with mswin.vim.
Remapping Alt+X to Ctrl+A prior to evoking mswin.vim solved my issue.
execute "set <A-x>=\ex"
noremap <A-x> <C-A>
source $VIMRUNTIME/mswin.vim
behave mswin
Now, Alt+X and Ctrl+X respectively increase and decrease numbers in Vim.
Mapping to Alt key combinations is often not evident in Vim; read more about this here.
A: I am using cygwin terminal + screen, so <c-a> is captured by the terminal multiplexer. I used this mapping:
:noremap <c-i> <c-a>
A: It seems that the CtrlA got mapped somewhere in startup.
As suggested before, use:
unmap <c-x>
I would use unmap, not nunmap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Load a form without showing it Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:
tasksForm.Visible = false;
tasksForm.Show();
Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.
When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:
tasksForm.WindowState = FormWindowState.Minimized;
tasksForm.Show();
I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.
A: It sounds to me like you need to sit down and re-think your approach here. I cannot imagine a single reason your public methods need to be in a form if you are not going to show it. Just make a new class.
A: I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist.
It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.
A: From MSDN:
Form.Load
Occurs before a form is displayed for the first time.
Meaning the only thing that would cause the form to load, is when it is displayed.
Form.Show(); and Form.Visible = true; are the exact same thing. Basically, behind the scenes, Show checks for various conditions, then sets Visible to true. So obviously, setting visible to false (which it already is) before showing the form is meaningless.
But let's forget the technicalities. I completely agree with Rich B and Shaun Austin - the logic shouldn't be in that form anyway.
A: Perhaps it should be noted here that you can cause the form's window to be created without showing the form. I think there could be legitimate situations for wanting to do this.
Anyway, good design or not, you can do that like this:
MyForm f = new MyForm();
IntPtr dummy = f.Handle; // forces the form Control to be created
I don't think this will cause Form_Load() to be called, but you will be able to call f.Invoke() at this point (which is what I was trying to do when I stumbled upon this SO question).
A: Sometimes this would be useful without it being bad design. Sometimes it could be the start of a migration from native to managed.
If you were migrating a c++ app to .NET for example, you may simply make yourwhole app a child window of the .NET form or panel, and gradually migrate over to the .NET by getting rid of your c++ app menu, status bar, toolbar and mapping teh .NEt ones to your app using platform invoke etc...
Your C++ app may take a while to load, but the .NET form doesn't..in which you may like to hide the .NEt form until your c++ app has initialised itself.
I'd set opacity=0 and visible=false to false after calling show, then when your c++ app loads, then reverse.
A: If you make the method public, then you could access it directly.... however, there could be some unexpected side effects when you call it. But making it public and calling it directly will not draw the screen or open the form.
A: Move mandatory initialization code for the form class out of the Load event handler into the constructor. For a Form class, instantiation of an instance (via the constructor), form loading and form visibility are three different things, and don't need to happen at the same time (although they do obviously need to happen in that order).
A: None of the answers solved the original question, so, add the below, call .Show() to load the form without showing it, then call .ShowForm() to allow it to be visible if you want to after:
private volatile bool _formVisible;
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(_formVisible);
}
public void ShowForm()
{
_formVisible = true;
if (InvokeRequired)
{
Invoke((Action) Show);
}
else
{
Show();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: What are some Search Servers out there? I'm looking to find alternatives to Solr from the Apache Software Foundation.
For those that don't know, Solr is an enterprise search server. A client application uses a web-services like interface to submit documents for indexing and also to perform search queries. Solr has other features built in like caching and replication. I believe it was originally started by CNet and then open-sourced.
I'm looking for other search servers out there that might be seen as the competition.
A: I wrote a long post about my experiences and features of all the engines I listed below but I scrapped it because formatting is a pita. But quite simply if you don't want to shell out money Solr/Lucene or Fast (now MSSE) is really about the best you can do.
Excluded because I have no experience of this product:
Seamark,
Price High to Low
*
*Endeca,
*FredHopper,
*Mercado,
*Google Mini,
*Microsoft Search Server,
*Autonomy,
*Microsoft Search Server Express,
*Solr/Lucene
Speed Fast to Slow
*
*Google Mini/Endeca,
*FredHopper,
*Autonomy,
*Solr/MSS/MSSE
Features High to Low
*
*Endeca,
*FredHopper,
*Mercado,
*Solr,
*Autonomy,
*Lucene,
*MSS/MSSE,
*Google Mini
Extensibility High to Low
*
*Solr/Lucene,
*Endeca,
*FredHopper,
*Mercado,
*Autonomy,
*MSS/MSSE,
*Google Mini
Java API
*
*Endeca,
*FredHopper,
*Autonomy,
*Solr/Lucene
.NET API
*
*Endeca,
*Solr/Lucene,
*MSS/MSSE,
*Autonomy
XML API
*
*FredHopper,
*Mercado,
*Solr/Lucene,
*Autonomy,
*Google Mini (limited)
Faceted Search
*
*Endeca,
*FredHopper,
*Seamark,
*Solr
Natural Language Search
*
*Endeca,
*Fred Hopper,
*Solr,
*Mercado,
*MSS/MSSE,
*Autonomy,
*Google Mini
Document Crawling
*
*Endeca,
*Mercado,
*MSS/MSSE,
*Autonomy,
*Google Mini
ITL
*
*Endeca,
*FredHopper
Merchandizing/Content Spotlighting
*
*Endeca,
*FredHopper,
*Mercado
Distributed Search
*
*Endeca,
*FredHopper,
*Mercado,
*Solr/Lucene,
*Autonomy,
*Google Mini
Analytics
*
*Endeca
Platform x86 Windows
*
*Endeca,
*FredHopper,
*Mercado,
*MSS/MSSE,
*Solr/Lucene,
*Autonomy
Platform x64 Windows
*
*Endeca,
*FredHopper,
*Solr/Lucene
Platform x86 Unix Variants
*
*Endeca,
*FredHopper,
*Mercado,
*Solr/Lucene,
*Autonomy
Platform x64 Unix Variants
*
*Endeca,
*Solr/Lucene
Other
*
*Google Mini
A: I've worked peripherally with Endeca, and it seems like a feature packed, fast engine.
They seem especially well suited towards eCommerce site driving, with special tools for customizing content for up-sells and cross-sells. I also think they are going to try and move into the BI space, so it should be an interesting combination of the two capabilities if they pull it off seamlessly.
A: I used to work at Endeca so take this for what it is. I won't comment on competitors, but I do really believe it's a significantly better product than anything else out there.
Solr provides basic faceted search, which is "good enough" for many applications. In a lot of ways, it's a low-end Endeca.
Some of the things Endeca would give you over Solr:
*
*better language analysis (stemming, etc.)
*Joins and the ability to do many-to-many filtering
*support for querying via XQuery
*better support for managing dimensions / facets
*much better performance (both for queries and pushing data in)
*crawlers and data integration tools
*better admin tools
And, obviously, services and support.
That said, it's not cheap, so if you don't have a budget for it, Solr isn't a bad option.
A: +1 for Lucene and FAST. Lucene has also been ported to .NET if you're interested in extending it.
http://incubator.apache.org/lucene.net/
A: Here are some more open source search engines
*
*Sphinx
*Xapian
*Zend_Search_Lucene
Here are some search related tools
*
*Forage The Forage PHP5 library is an easy to use interface to
multiple back end search libraries. It provides a common interface while
supporting unique features in each library by allowing back-ends to support
specific features or not.
*Marjory Marjory is a webservice for indexing and searching for
documents, utilizing a full-text search engine.
A: Fast ESP which Microsoft bought in January 2008
A: We are using Fast today. It's has many great features but we don't use them. It's expensive. We are in search for an alternate solution as well.
A: What about FACT-Finder? e.g. www.eddiebauer.de is using the search and navigation solution and more than 500 other european webshops. Highly error tolerant...
A: IBM Omnifind Yahoo Edition is an Enterprise search server which uses Apache Lucene for indexing. It is simple, easy to install and administer. It also has a built in Open Search API. It has multi-platform support and its Free!!
This product was launched by IBM to compete with Google Mini in the Enterprise Search market.
A: In addition to the ones that people already mentioned, Microsoft has "Microsoft Search Server" and "Microsoft Search Server Express". The latter is free, the former supports a larger corpus.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.