Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a jQuery script that changes the src attribute of an `<img>` and a few other page elements.
My script is hooked to the document-ready callback using `$()`. When I refresh the page I see the original content for half a second. I want to avoid that.
Is there a way for my script to execute **after** the DOM is ready but **before** it is rendered? | I don't think it's possible. These days, browsers begin rendering the UI before the DOM has finished building. | Not really, but you can fake it really well. Try setting the image to display='none'. After you've set the src attribute, you can reveal the image with $('#myImage').show(). | How to do something with jquery after the DOM is ready but before the UI is rendered? | [
"",
"javascript",
"jquery",
""
] |
Okay, so i've created my c# application, created an installer for it and have it working installed on my machine.
The problem is, when the user opens the application exe twice, there will be two instances of the application running. I only ever want one instance of the application to be running at any time, how do I go about doing this?
Thanks for your help, | The common technique for this is to create a named `Mutex` and check for its presence on application start.
See [this](http://www.ddj.com/windows/184416856) or [this](http://www.codeproject.com/KB/cs/CSSIApp.aspx).
Code from DDJ:
```
class App : Form
{
Mutex mutex;
App()
{
Text = "Single Instance!";
mutex = new Mutex(false, "SINGLE_INSTANCE_MUTEX");
if (!mutex.WaitOne(0, false))
{
mutex.Close();
mutex = null;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
mutex.ReleaseMutex();
base.Dispose(disposing);
}
static void Main()
{
App app = new App();
if (app.mutex != null) Application.Run(app);
else MessageBox.Show("Instance already running");
}
}
``` | i solved this problem by this
```
[STAThread]
static void Main()
{
Process[] result = Process.GetProcessesByName("ApplicationName");
if (result.Length > 1)
{
MessageBox.Show("There is already a instance running.", "Information");
System.Environment.Exit(0);
}
// here normal start
}
```
it is simple, but i had hardly time to check for better solutions. | Restrict multiple instances of an application | [
"",
"c#",
".net",
"c#-2.0",
"multiple-instances",
""
] |
I want to call the base class implementation of a virtual function using a member function pointer.
```
class Base {
public:
virtual void func() { cout << "base" << endl; }
};
class Derived: public Base {
public:
void func() { cout << "derived" << endl; }
void callFunc()
{
void (Base::*fp)() = &Base::func;
(this->*fp)(); // Derived::func will be called.
// In my application I store the pointer for later use,
// so I can't simply do Base::func().
}
};
```
In the code above the derived class implementation of func will be called from callFunc. Is there a way I can save a member function pointer that points to Base::func, or will I have to use `using` in some way?
In my actual application I use boost::bind to create a boost::function object in callFunc which I later use to call func from another part of my program. So if boost::bind or boost::function have some way of getting around this problem that would also help. | When you call a virtual method via a reference or a pointer you will always activate the virtual call mechanism that finds the most derived type.
Your best bet is to add an alternative function that is not virtual. | What you're trying to do unfortunately isn't possible. Pointer-to-member-functions are *designed* to maintain the virtualness of the function pointed-to. | Calling base class definition of virtual member function with function pointer | [
"",
"c++",
"virtual",
"function-pointers",
"boost-bind",
""
] |
I am making a web application in asp.net mvc C# with jquery that will have different pricing plans.
Of course the more you pay the more features you get.
So I was planning to use roles. So if someone buys plan 1 then they get a role of plan 1. Then on the page use an if statement to check if they are in certain roles. If they are allowed to use the feature generate it. If not do nothing.
It could be very well be that the entire page might be shared among all the roles except maybe one feature on that page.
Now someone was telling me that I should not do the way I am thinking of it since if I add more features then my page will get more cluttered with if statements and it will be hard to maintain.
They said I should treat each plan as a separate application. So if I have 2 plans have 2 different links going to different files.
I agree with the person that it probably will be better in the long run since I won't have to keep tacking on if statements but the thing that gets me is say in this scenario.
In the future versions of my site I will have SMS and Email alerts.
Right now I have a Html table with a set of tasks the user has to do. In future versions of the site I will give the option to get alerted by email OR SMS. If they choose say to be alerted by email in a table column an envelope will appear.
Now this might only be for people who are on Plan 2 and not Plan 1. So the solution of the person was just copy and paste all the code for the table code stick in a file called Plan2.aspx. Then add the new row for the icons to the newly pasted code for Plan 2.
Now I would have a Plan1 file that has everything the same except for this extra row that is in the Plan2 file.
So I am not too crazy about that idea because of duplicate code if something is wrong with the table I now have to change it into 2 locations not one. If I add a 3rd plan now I need to keep track of 3 sets of the same code with some varying differences.
My original way would have been that row in the table that is only for plan2 would be surrounded by an if statement checking their role.
Like in some cases I probably will be able to put all the common code into one partial control and all the different code in another partial control but its situations like this that I am not sure about.
There will be many more of these situations this just one example.
So what is the best way to make your code maintainable but also have minimal amounts of duplicate code.
Sorry for the post its kinda hard to describe what I am trying to achieve and situations that are that are could be possible areas of trouble.
---
Edit
---
So I am still kinda confused by the examples people have given and would love to see little full examples of them and not just stubs.
I was also thinking but I am not sure if this would be good practice or what and might look pretty strange and some parts.
Is to have everything in common in a partial view even if it is just like one line. Then have 2 separate links and just put the partial views together depending on their role.
I am thinking about the 2 seperate links because of the jquery stuff. Like for instance if I had this
```
<textbox code>
<textbox code> // this textbox code is only for plan 2 ppl. This textbox needs to go here
<textbox code>
```
Each of these textboxes tags would be in its own partial view(so 3 in this case)
so I would have 2 aspx pages.
1st
```
<render partialView 1>
<render partialView 2>
<render partialView 3>
```
2nd
```
<render partialView 1>
<render partialView 3>
```
Then in each of these 2 aspx pages would have different javascript files linked up.
The thing what I was thinking of if I just have like one javascript file with my jquery someone can just go and add the missing html ones and have access to all those features.
So I am not sure how I would write it if I am using the "if statement" way.
But at the same time have everything in partialView will look very funny. Like if I am making a table or something.
One partial view would have the start tag and some rows then X partial views down the road would have the closing tag.
Will look very weird and hard to see the whole picture since you will have to open up X amount of files to see the whole picture.
So there is got to be a better way. | Whilst it's not the best practice to have a view littered with if statements (see Rob Conery's [blog post](http://blog.wekeroad.com/blog/asp-net-mvc-avoiding-tag-soup/) on the matter), some rudimentary logic, is in my opinion, acceptable. If you do this though, you should try to use partials to keep the view as uncluttered as possible. This, as you pointed out is what you think is the best solution.
Your view logic really should be as simple as possible though and your models would benefit from inheriting your price plan information to save duplicating the code itself.
*Removed the other code, as you pointed out that you would just use the User class.*
Regarding the textbox, this could be trickier. One thought is that you could have your scripts folders which contain global JS, and then subfolders that have JS specifically for other roles (Role 2 and 3 for example). These could be protected by a custom route constraint which prevents users from accessing the file/folder without the relevant level of authentication. You should also use a web.config to provide a similar level of protection. That, or just use the web.config file. | How well abstracted are the components?
My naive approach would be to create a separate layer that dishes the components out to the UI. Something like a repository pattern, with a method like this:
```
public IEnumerable<PlanRestrictedFeature> GetFeaturesForPlan(Role r)
{
//return all features that the user has access to based on role
//this forces all this logic to exist in one place for maintainability
}
```
Of course, the method could also take in a string, enum, or Plan object, if you have one. Internally, this may use some type of map to make things simpler.
Then, the View can simply call the Render method of each component. Make sure the repository passes them back in the correct order for rendering, and rely on CSS for placement. | How to make maintainable code with minimal duplicate code? | [
"",
"c#",
"asp.net-mvc",
""
] |
What are the relative advantages / disadvantages of chaining classes together (or rather; using the results of one class to generate another), compared to nesting classes?
I'm trying to restructure my user / authentication system and am wondering whether;
* myAuthClass should act as a utility and if log-in is successful, simply create a new myUserClass object
* or whether the myAuthClass should create the myUserClass internally (ie $this->user = new myUserClass)
* or even if myUserClass should just call myAuthClass when necessary (ie when a user tries to log in) and update its internal structure (new emails, favourites, cart, etc) as necessary.
As you can tell I'm a bit of an OOP n00b. Concpetually I seem to be able to make a case for each of the methods, so I'm interested in hearing from other people regarding the +ves/-ves of the various approaches.
Cheers. | From an accademic perspective, all 3 options are incorrect in that they are programmed against concrete implementations and not against an abstract interface. As such they are directly coupled together, which limits reuse - you re-use them both or not at all.
You could generate IUserClass, or IAuthClass and implement this abstract interface into a concrete class and then I would go for a situation where the auth class implementation took an IUserClass when authenticating to populate, or the user class was given an implementation of IAuthClass to authenticate against.
In each scenario this allows the most flexability, in that the auth class can be reused and different versions of the UserClass can be generated, or the user class has the ability to use multiple different authentication mechanisms, as long as the inherit from IAuthClass.
The latter approach of giving the user class an authentication object (that implements IAuthClass) would be my preference, in that authentication mechanisms differ, even with a single application, whilst the user class would change less. But to be correct, neither should be based on a concrete implementation.
This can however be seen as over the top, so it's a judgement call. | First of all I suggest you to use the adapter pattern. You should have an abstract class that define the interface (the public methods) than you create a class that implements a particular type of authentication. For instance you can create a class/adapter for DB base authentication, one for LADP authentication.. etc...
The best thing instead of reinventing the wheel, you should use a ready made solution. I have used Zend\_Auth, which implements the adapter pattern. By using Zend\_Auth you can understand good OOP practicies, the adapter pattern, the use of interfaces and abstract classes, if you want to.
Here you can see how I have used Zend\_Auth for an intranet;
```
protected function Authentication() {
$strEmail = trim($this->txtEmail->Text);
$this->txtPassword->Text = trim($this->txtPassword->Text);
// do the process of authentication, AD and then DB
// Get a reference to the singleton instance of QAuth
$auth = QAuth::getInstance();
// Set up the authentication adapter
$authAdapter = new QAuth_Adapter_WebService(__LOGIN_WS_URL__,
$strEmail, $this->txtPassword->Text
);
// Attempt authentication, saving the result
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$objUser = User::LoadByEmail($strEmail);
// if there is not a user's record create one
if(!$objUser) {
$this->User_Create($strEmail);
$objUser = User::LoadByEmail($strEmail);
}
$crypt = new Encryption();
$encr = $crypt->encrypt(__KEY__, $objUser->UserID);
$_SESSION['user_id'] = $encr;
setcookie('user_id', $_SESSION['user_id'], time()+(3600*24*365*20));
$this->Intranet1Integration($objUser->UserID);
QApplication::Redirect('http://'.__URL__.'/index.php');
}
else {
QApplication::DisplayAlert(
'Log on failed. You must provide a Company email and a correct password.'
);
}
}
``` | OOP design approach for two interacting classes | [
"",
"php",
"design-patterns",
"oop",
""
] |
Is there any way to turn off all `console.log` statements in my JavaScript code, for testing purposes? | Redefine the console.log function in your script.
```
console.log = function() {}
```
That's it, no more messages to console.
**EDIT:**
Expanding on Cide's idea. A custom logger which you can use to toggle logging on/off from your code.
From my Firefox console:

```
var logger = function()
{
var oldConsoleLog = null;
var pub = {};
pub.enableLogger = function enableLogger()
{
if(oldConsoleLog == null)
return;
window['console']['log'] = oldConsoleLog;
};
pub.disableLogger = function disableLogger()
{
oldConsoleLog = console.log;
window['console']['log'] = function() {};
};
return pub;
}();
$(document).ready(
function()
{
console.log('hello');
logger.disableLogger();
console.log('hi', 'hiya');
console.log('this wont show up in console');
logger.enableLogger();
console.log('This will show up!');
}
);
```
How to use the above 'logger'? In your ready event, call logger.disableLogger so that console messages are not logged. Add calls to logger.enableLogger and logger.disableLogger inside the method for which you want to log messages to the console. | The following is more thorough:
```
var DEBUG = false;
if(!DEBUG){
if(!window.console) window.console = {};
var methods = ["log", "debug", "warn", "info"];
for(var i=0;i<methods.length;i++){
console[methods[i]] = function(){};
}
}
```
This will zero out the common methods in the console if it exists, and they can be called without error and virtually no performance overhead. In the case of a browser like IE6 with no console, the dummy methods will be created to prevent errors. Of course there are many more functions in Firebug, like trace, profile, time, etc. They can be added to the list if you use them in your code.
You can also check if the debugger has those special methods or not (ie, IE) and zero out the ones it does not support:
```
if(window.console && !console.dir){
var methods = ["dir", "dirxml", "trace", "profile"]; //etc etc
for(var i=0;i<methods.length;i++){
console[methods[i]] = function(){};
}
}
``` | How to quickly and conveniently disable all console.log statements in my code? | [
"",
"javascript",
"debugging",
"console",
""
] |
Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code. | The best solution is the [Unum](https://github.com/trzemecki/Unum) package. a de-facto standard, imho. | [quantities](https://github.com/python-quantities/python-quantities) seems to be gaining a lot of traction lately. | Is there a standard pythonic way to treat physical units / quantities in python? | [
"",
"python",
"physics",
"units-of-measurement",
""
] |
I have the following Java code to fetch the entire contents of an HTML page at a given URL. Can this be done in a more efficient way? Any improvements are welcome.
```
public static String getHTML(final String url) throws IOException {
if (url == null || url.length() == 0) {
throw new IllegalArgumentException("url cannot be null or empty");
}
final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
final BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuilder page = new StringBuilder();
final String lineEnd = System.getProperty("line.separator");
String line;
try {
while (true) {
line = buf.readLine();
if (line == null) {
break;
}
page.append(line).append(lineEnd);
}
} finally {
buf.close();
}
return page.toString();
}
```
I can't help but feel that the line reading is less than optimal. I know that I'm possibly masking a `MalformedURLException` caused by the `openConnection` call, and I'm okay with that.
My function also has the side-effect of making the HTML String have the correct line terminators for the current system. This isn't a requirement.
I realize that network IO will probably dwarf the time it takes to read in the HTML, but I'd still like to know this is optimal.
On a side note: It would be awesome if `StringBuilder` had a constructor for an open `InputStream` that would simply take all the contents of the `InputStream` and read it into the `StringBuilder`. | As seen in the other answers, there are many different edge cases (HTTP peculiarities, encoding, chunking, etc) that should be accounted for in any robust solution. Therefore I propose that in anything other than a toy program you use the de facto Java standard HTTP library: [Apache HTTP Components HTTP Client](https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/).
They provide many samples, ["just" getting the response contents for a request looks like this](https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientWithResponseHandler.java):
```
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.google.com/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
// responseBody now contains the contents of the page
System.out.println(responseBody);
httpclient.getConnectionManager().shutdown();
``` | OK, edited once more. Be sure to put your try-finally blocks around it, or catch IOException
```
...
final static int BUFZ = 4096;
StringBuilder page = new StringBuilder();
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
InputStream is = conn.getInputStream()
// perhaps allocate this one time and reuse if you
//call this method a lot.
byte[] buf = new byte[BUFZ] ;
int nRead = 0;
while((nRead = is.read(buf, 0, BUFZ) > 0) {
page.append(new String(buf /* , Charset charset */));
// uses local default char encoding for now
}
```
Here try this one:
```
...
final static int MAX_SIZE = 10000000;
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
InputStream is = conn.getInputStream()
// perhaps allocate this one time and reuse if you
//call this method a lot.
byte[] buf = new byte[MAX_SIZE] ;
int nRead = 0;
int total = 0;
// you could also use ArrayList so that you could dynamically
// resize or there are other ways to resize an array also
while(total < MAX_SIZE && (nRead = is.read(buf) > 0) {
total += nRead;
}
...
// do something with buf array of length total
```
OK the code below was not working for you because the Content-length header line is not being sent in the beginning due to HTTP/1.1 "chunking"
```
...
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
InputStream is = conn.getInputStream()
int cLen = conn.getContentLength() ;
byte[] buf = new byte[cLen] ;
int nRead=0 ;
while(nRead < cLen) {
nRead += is.read(buf, nRead, cLen - nRead) ;
}
...
// do something with buf array
``` | What is the optimal way for reading the contents of a webpage into a string in Java? | [
"",
"java",
"string",
"optimization",
"inputstream",
"micro-optimization",
""
] |
FYI, ShadowBox is a javscript media viewer/lightbox. <http://www.shadowbox-js.com/>
---
Running into an issue when trying to dynamically load SWFs into my ShadowBox.
My script outputs the following HTML:
```
<div id="LightBoxItemList">
<a href="Images/large01.jpg" rel="shadowbox[Mixed];" class="First" />
<a href="Images/Hydro_Sample.swf" rel="shadowbox[Mixed];width: 800;height: 600;" />
<a href="Images/large01.jpg" rel="shadowbox[Mixed];" />
</div>
```
After this HTML is created and inserted into my page, I run the following script:
```
Shadowbox.clearCache();
Shadowbox.setup("#LightBoxItemList a");
```
Everything loads correct except the SWF. The SWF loads with a width and height of 300x300. I'm not sure what I'm doing wrong, but any advice would be awesome. Also, I'm running init() with skipSetup.
---
I would also note that if I put in the HTML into the sample statically (not through an AJAX call), it works correctly after my Shadowbox.Init() (with skipSetup taken out).
So it looks like setup() isn't doing what it should be doing. Or I'm doing it wrong.
Any suggestions would be greatly appreciated! | It is a quirk in ShadowBox. | You need to use `=` after width and height. Not `:`.
```
shadowbox[Mixed];width=600;height=200;
``` | Dynamically loading a SWF into ShadowBox | [
"",
"javascript",
"jquery",
"flash",
"shadowbox",
""
] |
In a recent question asked recently my simple minded answer highlighted many of my misconceptions about Java, the JVM, and how the code gets compiled and run. This has created a desire in me to take my understanding to a lower level. I have no problems with the low level understanding like assembly how ever bytecode and the JVM confound me. How object oriented code gets broken down on a low level is lost to me. I was wondering if anyone had any suggestion on how to learn about the JVM, bytecode and the lower level functioning of Java. Are there any utilities out there that allow you to write and run bytecode directly as I believe hands on experience with something is the best way to grow in understanding of it? Additionally and reading suggestions on this topic would be appreciated.
Edit: Secondary question. So I have a kinda sub question, the answers gave me an interesting idea to learn about the jvm, what would the plausibility of writing a really simple language like brainf\*\*k or Ook only in a readable syntax (maybe I could even develop it to support oo eventually) that compiles into bytecode be? Would that be a good learning experience? | Suggested reading: [the JVM spec](http://java.sun.com/docs/books/jvms/).
You might also want to play with [BCEL](http://jakarta.apache.org/bcel/) - there are other libraries around for manipulating bytecode, but that's probably the best known one. | The [Apache BCEL](http://jakarta.apache.org/bcel/) will allow you to analyse and hand craft .class files from bytecode.
[javap](http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javap.html) will allow you to disassemble existing .class files. It's particularly useful for knocking up quick test classes to understand what is really going on underneath the covers. | Learning about Java bytecode and the JVM | [
"",
"java",
"jvm",
"bytecode",
"low-level-code",
""
] |
What is the difference between event objects and condition variables?
I am asking in context of WIN32 API. | Event objects are kernel-level objects. They can be shared across process boundaries, and are supported on all Windows OS versions. They can be used as their own standalone locks to shared resources, if desired. Since they are kernel objects, the OS has limitations on the number of available events that can be allocated at a time.
Condition Variables are user-level objects. They cannot be shared across process boundaries, and are only supported on Vista/2008 and later. They do not act as their own locks, but require a separate lock to be associated with them, such as a critical section. Since they are user- objects, the number of available variables is limited by available memory. When a Conditional Variable is put to sleep, it automatically releases the specified lock object so another thread can acquire it. When the Conditional Variable wakes up, it automatically re-acquires the specified lock object again.
In terms of functionality, think of a Conditional Variable as a logical combination of two objects working together - a [keyed event](http://joeduffyblog.com/2006/11/28/windows-keyed-events-critical-sections-and-new-vista-synchronization-features/) and a lock object. When the Condition Variable is put to sleep, it resets the event, releases the lock, waits for the event to be signaled, and then re-acquires the lock. For instance, if you use a critical section as the lock object, `SleepConditionalVariableCS()` is similar to a sequence of calls to `ResetEvent()`, `LeaveCriticalSection()`, `WaitForSingleObject()`, and `EnterCriticalSection()`. Whereas if you use a SRWL as the lock, `SleepConditionVariableSRW()` is similar to a sequence of calls to `ResetEvent()`, `ReleaseSRWLock...()`, `WaitForSingleObject()`, and `AcquireSRWLock...()`. | They are very similar, but event objects work across process boundaries, whereas condition variables do not. From the [MSDN documentation on condition variables](http://msdn.microsoft.com/en-us/library/ms682052%28VS.85%29.aspx):
> Condition variables are user-mode
> objects that cannot be shared across
> processes.
From the [MSDN documentation on event objects](http://msdn.microsoft.com/en-us/library/ms682655%28VS.85%29.aspx):
> Threads in other processes can open a
> handle to an existing event object by
> specifying its name in a call to the
> OpenEvent function. | Difference between event object and condition variable | [
"",
"c++",
"multithreading",
"winapi",
"synchronization",
""
] |
I've got a **MenuManager** class to which each module can add a key and and element to be loaded into the main content:
```
private Dictionary<string,object> _mainContentItems = new Dictionary<string,object>();
public Dictionary<string,object> MainContentItems
{
get { return _mainContentItems; }
set { _mainContentItems = value; }
}
```
So the customer module registers its views like this:
```
layoutManager.MainContentViews.Add("customer-help", this.container.Resolve<HelpView>());
layoutManager.MainContentViews.Add("customer-main", this.container.Resolve<MainView>());
```
So then later to bring a specific view to the front I say:
```
layoutManager.ShowMainContentView("customer-help");
```
And to get the default view (first view registered), I say:
```
layoutManager.ShowDefaultView("customer");
```
And this works fine.
However, I want to eliminate the "code smell" with the hyphen which separates module name and view name, so I would like to register with this command:
```
layoutManager.MainContentViews.Add("customer","help", this.container.Resolve<HelpView>());
```
**But what is the best way to replace my current Dictionary, e.g. what comes to mind are these:**
* `Dictionary<string, string, object> (doesn't exist)`
* `Dictionary<KeyValuePair<string,string>, object>`
* `Dictionary<CUSTOM_STRUCT, object>`
The new collection needs to be able to do this:
* get a view with module and view key (e.g. "customer", "help" returns 1 view)
* get a collection of all views by module key (e.g. "customer" returns 5 views) | Strictly meeting your criteria, use a `Dictionary<string, Dictionary<string, object>>` ;
```
var dict = new Dictionary<string, Dictionary<string, object>>();
...
object view = dict["customer"]["help"];
Dictionary<string, object>.ValueCollection views = dict["customer"].Values;
``` | As mentioned in a [similar thread](https://stackoverflow.com/questions/5853141/collection-requiring-two-keys-to-a-unique-value-in-c-sharp), a good way to represent a 2-key dictionary in .NET 4 is to use the [Tuple](http://msdn.microsoft.com/en-us/library/system.tuple.aspx/ "Tuple class") class:
```
IDictionary<Tuple<K1, K2>, V>
``` | What is the best C# collection with two keys and an object? | [
"",
"c#",
"wpf",
"collections",
"prism",
""
] |
I'm trying to debug a huge, antiquated (circa 2001) PHP web service and I'm encountering file open failures. The fopen call is in an included module, the caller is logging that the file could not be opened but no reason is being logged.
The code that actually does the open is:
```
// Read the file
if (!($fp = @fopen($fileName, 'rb'))) {
$errStr = "Failed to open '{$fileName}' for read.";
break; // try-block
}
```
How can I find out why fopen failed? | Great answers have already been given, about the [@ operator](http://php.net/manual/en/language.operators.errorcontrol.php), but here's a couple of more informations that could be useful, either to you or someone else :
* If, for debugging purposes, you need the disable the `@ operator`, you can install the [scream extension](http://pecl.php.net/package/scream) *-- see also [the manual](http://php.net/scream) --* which is really useful when you're maintaining some kind of old application not well designed / coded ^^
* Depending on your PHP configuation *(if the [`track_errors`](http://us.php.net/manual/en/errorfunc.configuration.php#ini.track-errors) option is activated)*, you might be able to use [`$php_errormsg`](http://us.php.net/manual/en/reserved.variables.phperrormsg.php) to get the last error message.
Considering this piece of code :
```
// This file doesn't exist
if (!@fopen('/tmp/non-existant-file.txt', 'r')) {
var_dump($php_errormsg);
}
// My Apache server doesn't have the right to read this file
if (!@fopen('/tmp/vboxdrv-Module.symvers', 'w')) {
var_dump($php_errormsg);
}
```
You would get this :
```
string 'fopen(/tmp/non-existant-file.txt) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: No such file or directory' (length=129)
string 'fopen(/tmp/vboxdrv-Module.symvers) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: Permission denied' (length=122)
```
So, real, useful, meaningful, error messages **;-)** | Take away the @ sign.
The @ sign suppresses error messages, so it is supressing the error the the function would normally give. | How to output the reason for a PHP file open failure | [
"",
"php",
"fopen",
"error-reporting",
""
] |
I have a table with number of page views per day. Something like this:
```
+------+------------+------+
| id | date | hits |
+------+------------+------+
| 4876 | 2009-07-14 | 4362 |
+------+------------+------+
| 4876 | 2009-07-15 | 1324 |
+------+------------+------+
| 7653 | 2009-06-09 | 5643 |
+------+------------+------+
```
I need to create a function that compares the total hits between last two weeks and get the porcentage of change (popularity).
If the first week I have 1000 hits and the second week 2000 hits I have +200% of popularity
[ (1000 \* 2000) / 100 ] = 200
If the first week I have more hits than in the second week the popularity will be in minus (-80% for example)
I have some questions:
1) I'm using the correct math formula??
2) How I select in MySQL the last two weeks from now?
3) Its possible that the first week we have hits, but the second week no hits at all so the table row will be empty for those dates or those specific days that there were no hits.. Is this a problem?
4) I'm sure there is a better way for doing this kind of statistics.. Some better ideas???? | Use this:
```
<?php
function fetch($sql)
{
$query = mysql_query($sql);
return mysql_fetch_assoc($query);
}
function calculate($week1, $week2)
{
if ($week1 == 0)
{
$week1 = 1;
}
return ($week2 / $week1) * 100;
}
$q1 = "SELECT SUM(hits) as hits FROM table WHERE DATE_SUB(CURDATE(),INTERVAL 1 week) <= date";
$first_week_hits = fetch($q1);
$q2 = "SELECT SUM(hits) as hits FROM table WHERE DATE_SUB(CURDATE(),INTERVAL 2 week) <= date";
$second_week_hits = fetch($q2);
$percent = $str_percent = calculate($first_week_hits['hits'], $second_week_hits['hits']);
if ($percent > 0)
{
$str_percent = '+'.$percent; // :)
}
echo "I have ".$str_percent."% of popularity";
?>
``` | 1) Not quite. I think you want the percentage change. Going from 1000 hits to 2000 hits is an increase of 100%, not 200%. You want ((2000 - 1000)/100);
2) Two weeks ago: `SELECT SUM(hits) as s FROM tbl WHERE date>=NOW() - INTERVAL 2 WEEK AND date<NOW()-INTERVAL 1 WEEK`
One week ago: `SELECT SUM(hits) as s FROM tbl WHERE date>=NOW()-INTERVAL 1 WEEK`
3) Not with the query above. Any date gaps will simply not be part of the `SUM()`.
4) This method seems pretty good to me actually. It should get the job done. | MySQL / PHP: Date functions for page view statistics and popularity | [
"",
"php",
"mysql",
"database",
"datetime",
"statistics",
""
] |
I'm using an ICEFaces application that runs over JBOSS, my currently heapsize is set to
-Xms1024m –Xmx1024m -XX:MaxPermSize=256m
what is your recommendation to adjust memory parameters for JBOSS AS 5 (5.0.1 GA) JVM 6? | According to this [article](http://www.jboss.org/community/wiki/CargoMavenplugin-raisingPermGenforJBossAS5):
> AS 5 is known to be greedy when it comes to [PermGen](http://codingclues.eu/2008/permgen-space-exceptions-with-maven-due-to-memory-leak/). When starting, it often throws `OutOfMemoryException: PermGen Error`.
This can be particularly annoying during development when you are hot deploying frequently an application. In this case, JBoss QA recommends to *raise the permgen size, allow classes unloading and permgen sweep*:
```
-XX:PermSize=512m -XX:MaxPermSize=1024 -XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled
```
But this is more FYI, I'm not suggesting to apply this configuration blindly (as people wrote in comments, "if it ain't broken, don't fix it").
Regarding your heap size, always keep in mind: *the bigger the heap, the longer the major GC*. Now, when you say "it was definitely too small", I don't really know what this means (what errors, symptoms, etc). To my knowledge, a 1024m heap is actually pretty big for a webapp and should really be more than enough for most of them. Just beware of the major GC duration. | Heap: Start with 512 MB, set the cap to where you believe your app should never get, and not to make your server start swapping.
Permgen: That's usually stable enough, once the app reads all classes used in the app. If you have tested the app and it works with 256 MB, then leave it so. | How is your JVM 6 memory setting for JBOSS AS 5? | [
"",
"java",
"jboss",
"jvm",
"settings",
""
] |
Take the following:
```
class A {}
class B : A {}
class C
{
C()
{
var b = new B();
Foo(b);
Foo2(ref b); // <= compile-time error:
// "The 'ref' argument doesn't match the parameter type"
}
void Foo(A a) {}
void Foo2(ref A a) {}
}
```
Why does the above compile-time error occur? This happens with both `ref` and `out` arguments. | =============
UPDATE: I used this answer as the basis for this blog entry:
[Why do ref and out parameters not allow type variation?](http://blogs.msdn.com/ericlippert/archive/2009/09/21/why-do-ref-and-out-parameters-not-allow-type-variation.aspx)
See the blog page for more commentary on this issue. Thanks for the great question.
=============
Let's suppose you have classes `Animal`, `Mammal`, `Reptile`, `Giraffe`, `Turtle` and `Tiger`, with the obvious subclassing relationships.
Now suppose you have a method `void M(ref Mammal m)`. `M` can both read and write `m`.
---
> Can you pass a variable of type `Animal` to `M`?
No. That variable could contain a `Turtle`, but `M` will assume that it contains only Mammals. A `Turtle` is not a `Mammal`.
**Conclusion 1**: `ref` parameters cannot be made "bigger". (There are more animals than mammals, so the variable is getting "bigger" because it can contain more things.)
---
> Can you pass a variable of type `Giraffe` to `M`?
No. `M` can write to `m`, and `M` might want to write a `Tiger` into `m`. Now you've put a `Tiger` into a variable which is actually of type `Giraffe`.
**Conclusion 2**: `ref` parameters cannot be made "smaller".
---
Now consider `N(out Mammal n)`.
> Can you pass a variable of type `Giraffe` to `N`?
No. `N` can write to `n`, and `N` might want to write a `Tiger`.
**Conclusion 3**: `out` parameters cannot be made "smaller".
---
> Can you pass a variable of type `Animal` to `N`?
Hmm.
Well, why not? `N` cannot read from `n`, it can only write to it, right? You write a `Tiger` to a variable of type `Animal` and you're all set, right?
Wrong. The rule is not "`N` can only write to `n`".
The rules are, briefly:
1) `N` has to write to `n` before `N` returns normally. (If `N` throws, all bets are off.)
2) `N` has to write something to `n` before it reads something from `n`.
That permits this sequence of events:
* Declare a field `x` of type `Animal`.
* Pass `x` as an `out` parameter to `N`.
* `N` writes a `Tiger` into `n`, which is an alias for `x`.
* On another thread, someone writes a `Turtle` into `x`.
* `N` attempts to read the contents of `n`, and discovers a `Turtle` in what it thinks is a variable of type `Mammal`.
Clearly we want to make that illegal.
**Conclusion 4**: `out` parameters cannot be made "larger".
---
*Final conclusion*: **Neither `ref` nor `out` parameters may vary their types. To do otherwise is to break verifiable type safety.**
If these issues in basic type theory interest you, consider reading [my series on how covariance and contravariance work in C# 4.0](http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx). | Because in both cases you must be able to assign value to ref/out parameter.
If you try to pass b into Foo2 method as reference, and in Foo2 you try to assing a = new A(), this would be invalid.
Same reason you can't write:
```
B b = new A();
``` | Why doesn't 'ref' and 'out' support polymorphism? | [
"",
"c#",
"polymorphism",
"out-parameters",
"ref-parameters",
""
] |
when i run my hibernate tools
it reads from the db and create java classes for each tables,
and a java class for composite primary keys.
that's great.
the problem is this line
```
@Table(name="tst_feature"
,catalog="tstdb"
)
```
while the table name is required, the "catalog" attribute is not required.
sometimes i want to use "tstdb", sometimes i want to use "tstdev"
i thought which db was chosen depends on the jdbc connection url
but when i change the jdbc url to point to "tstdev", it is still using "tstdb"
so,
i know what must be done,
just don't know how its is done
my options are
* suppress the generation of the "catalog" attribute
currently i'm doing this manually (not very productive)
or i could write a program that parses the java file and remove the attribute manually
but i'm hoping i don't have to
OR
* find a way to tell hibernate to ignore the "catalog" attribute and use the schema that is explicitly specified.
i don't know the exact setting i have to change to achive this, or even if the option is available. | You need to follow 3 steps -
1) In the `hibernate.cfg.xml`, add this property
```
hibernate.default_catalog = MyDatabaseName
```
(as specified in above post)
2) In the `hibernate.reveng.xml`, add all the table filters like this
```
table-filter match-name="MyTableName"
```
(just this, no catalog name here)
3) Regenerate hibernate code
You will not see any catalog name in any of the `*.hbm.xml` files.
I have used Eclipse Galileo and Hibernate-3.2.4.GA. | There is a customization to the generation, that will tell what tables to put in what catalog.
You can specify the catalogue manually (in reveng file, `<table>` element), or programmatically (in your custom ReverseEngineeringStrategy class if I remember well).
Also, I recently had to modify the generation templates.
See the reference documentation :
* <http://docs.jboss.org/tools/archive/3.0.1.GA/en/hibernatetools/html_single/index.html#hibernaterevengxmlfile>
you can customize the catalogue of each of your tables manually
* <https://www.hibernate.org/hib_docs/tools/viewlets/custom_reverse_engineering.htm> watch a movie that explains a lot ...
* <http://docs.jboss.org/tools/archive/3.0.1.GA/en/hibernatetools/html_single/index.html#d0e5363> for customizing the templates (I start with the directory that's closest to my needs, copy all of them in my own directory, then edit as will)
Sorry, this could get more precise, but I don't have access to my work computer right now. | Running hibernate tool annotation generation without the "catalog" attribute | [
"",
"java",
"hibernate",
"code-generation",
"annotations",
""
] |
what's an unmanaged COM code? and Single Threading Apartment? Thank you! | It means, "here are the key phrases you should look up and understand". No, this is not a snide remark. These concepts are involved and complicated and a single textbox is not the right place to try to explain them.
You can also ask that someone what s/he meant.
In the mean time, you could read [An Overview of Managed/Unmanaged Code Interoperability](http://msdn.microsoft.com/en-us/library/ms973872.aspx) and [Processes, Threads, and Apartments](http://msdn.microsoft.com/en-us/library/ms693344%28VS.85%29.aspx). | To make a long story short:
Unmanaged COM code means that there's no garbage collector available for that code. The COM code deal with its own memory, the .NET garbage collector shouldn't try to collect that memory.
The single threaded apartment is a model in which every COM messages are serialized/deserialized between objects. The messages are pumped through the windows messaging model, so that the COM objects don't need to care about thread-safety issues. In the multi-threaded apartment, the messages sent to an object can occur at any time, so that the objects must be thread-safe.
This is a *very* simplified explanation. More details about the single-threaded apartment [here](http://msdn.microsoft.com/en-us/library/ms680112(VS.85).aspx). | What does it mean when someone says "C# program should communicate with unmanaged COM code using the Single Threading Apartment" | [
"",
"c#",
""
] |
Can anyone recommend a source control solution for Visual Studio? I am going to be the only person using it, I just need something to back up my data every so often or before I undertake a big change in the software. I tried AnkhSVN, but this requires an SVN server. Is there anything that can be used locally that takes the pain out of copying solution folders manually? | With [Subversion](https://subversion.apache.org/) you can create local, file-system-based repositories for single-user access.
Probably the easiest way to use subversion (on windows) is to install [TortoiseSVN](https://tortoisesvn.net/). To create a repository, you simply create an empty folder in the location where you want the repository to be, right click that folder and select "TortoiseSVN -> Create repository here".
It is even possible (but not recommended) to create such a repository on a network share.
You can then access local repositories using a file-URL e.g: `file:///D:/Projects/MyRepository`
If you later find out that you need a server (e.g. to give other users access to the repository), you can easily install svnserve on a server and move the local repository to that server.
---
Just for completeness: as others have noted, there are several good clients for subversion (personally I'm using mainly TortoiseSVN and AnkhSVN):
* the [subversion command line binaries](https://subversion.apache.org/)
* [TortoiseSVN](http://tortoisesvn.tigris.org/) (free, integrated into windows explorer)
* [VSFileExplorer](http://www.mindscape.co.nz/products/vsfileexplorer/default.aspx) (free, gives you an explorer view inside Visual Studio and a allows you to access TortoiseSVN from there)
* [AnkhSVN](http://ankhsvn.open.collab.net/) (free, integrated into Visual Studio)
* [VisualSVN](http://www.visualsvn.com/visualsvn/) (commercial, integrated into Visual Studio)
* [VisualSVN Server](http://www.visualsvn.com/server/) (free, a SVN server with a nice GUI) | Funny nobody mentioned Git just yet. Granted, it does have a learning curve, but I've been using it successfully within Visual Studio for the past year. Both commandline and with a GUI ([GitExtensions](http://code.google.com/p/gitextensions/downloads/list)).
Download Git for Windows from [here.](http://code.google.com/p/msysgit/downloads/list)
Since it is a DVCS, it doesn't need a server. You can work against your local repositories publishing them to the world when needed (check out [Github](http://github.com/)). | Source control for Visual Studio that doesn't require a server? | [
"",
"c#",
".net",
"visual-studio",
"svn",
"version-control",
""
] |
I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.
Simulated sample code:
```
<a href="#button1" id="button1">button 1</a>
<a href="#button2" id="button2">button 2</a>
<a href="#" id="reset">Home</a>
```
So if you were to click on the "button 1" link, the url could be <http://example.com/foo.php#button1>
Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change. | I'm probably missing something, but why not just give them different IDs?
```
<a href="#button1" id="button-1">button 1</a>
<a href="#button2" id="button-2">button 2</a>
<a href="#" id="reset">Home</a>
```
Or whatever convention you'd prefer. | The whole point of an anchor link is to scroll a page to a particular point. So if you don't want that to happen, you need to attach an `onclick` handler and return false. Even just adding it as an attribute should work:
```
<a href="#button1" id="button1" onclick="return false">button 1</a>
```
A side of effect of the above is that the URL itself won't change, since returning false will cancel the event. So since you want the URL to actually change, you can set the `window.location.hash` variable to the value that you want (that is the only property of the URL that you can change without the browser forcing a reload). You can probably attach an event handler and call something like `window.location.hash = this.id` though I'm not sure how mootools handles events.
(Also you need all of the IDs to be unique) | HTML anchor link with no scroll or jump | [
"",
"javascript",
"html",
"xhtml",
"scroll",
"anchor",
""
] |
Consider the need for a function in C# that will test whether a string is a numeric value.
The requirements:
* must return a boolean.
* function should be able to allow for whole numbers, decimals, and negatives.
* assume no `using Microsoft.VisualBasic` to call into `IsNumeric()`. Here's a case of reinventing the wheel, but the exercise is good.
Current implementation:
```
//determine whether the input value is a number
public static bool IsNumeric(string someValue)
{
Regex isNumber = new Regex(@"^\d+$");
try
{
Match m = isNumber.Match(someValue);
return m.Success;
}
catch (FormatException)
{return false;}
}
```
**Question**: how can this be improved so that the regex would match negatives and decimals? Any radical improvements that you'd make? | Just off of the top of my head - why not just use `double.TryParse` ? I mean, unless you really want a regexp solution - which I'm not sure you really need in this case :) | Can you just use .TryParse?
```
int x;
double y;
string spork = "-3.14";
if (int.TryParse(spork, out x))
Console.WriteLine("Yay it's an int (boy)!");
if (double.TryParse(spork, out y))
Console.WriteLine("Yay it's an double (girl)!");
``` | .NET testing a string for numeric value | [
"",
"c#",
"regex",
"algorithm",
""
] |
> **Possible Duplicate:**
> [HTTP authentication logout via PHP](https://stackoverflow.com/questions/449788/http-authentication-logout-via-php)
Hi
I have a some functionality on my website protected using `.htaccess` and `.htpasswd`.
When users attempt to access this, they get prompt to enter details. They enter their details and get in and can see stuff etc. All works fine.
My question is how do I create a `logout` functionality for this type of authentication. I know that they can close the browser window to "Logout". But this is not ideal. What would you suggest to me?
Thanks. | Browsers usually don't support this, see [How do I log out?](http://httpd.apache.org/docs/1.3/howto/auth.html)
> Since browsers first started
> implementing basic authentication,
> website administrators have wanted to
> know how to let the user log out.
> Since the browser caches the username
> and password with the authentication
> realm, as described earlier in this
> tutorial, this is not a function of
> the server configuration, but is a
> question of getting the browser to
> forget the credential information, so
> that the next time the resource is
> requested, the username and password
> must be supplied again. There are
> numerous situations in which this is
> desirable, such as when using a
> browser in a public location, and not
> wishing to leave the browser logged
> in, so that the next person can get
> into your bank account.
>
> However, although this is perhaps the
> most frequently asked question about
> basic authentication, thus far none of
> the major browser manufacturers have
> seen this as being a desirable feature
> to put into their products.
>
> **Consequently, the answer to this
> question is, you can't. Sorry.**
There are browser extensions that allow you to clear the HTTP authentication for a site.
For Firefox the **[WebDeveloper](http://chrispederick.com/work/web-developer/)** extension (which is one of my favourtie extensions anyway) offers this feature.
The menu for this is `Miscellaneous/Clear Private Data/HTTP Authentication`. | **Tested on firefox and chrome**. What you can do is send the user to <http://logout:logout@example.com>. This will replace their current username/password with logout/logout (it could be any invalid user/pass combination) and since they now have the wrong username/password, they will have to login again to access the site.
On opera this does not work, because you can have several usernames/passwords at the same time. It didn't work on IE either, because IE does not appear to support <http://username:password@example.com> URLs. | How to logout when using .htaccess (and .htpasswd) authentication? | [
"",
"php",
"authentication",
".htaccess",
"logout",
".htpasswd",
""
] |
In the past, I've handled user image uploads in two different ways:
* Save the image data in a database table, and load it via a PHP script
* Upload the image, convert it to jpeg, put it in a directory and load it via HTML tags
The first option worked fairly well, but I had to keep fairly constraining size restrictions on uploaded images. The second option kind of worked, except for PHP's image library would often botch the file conversion (I think that can be fixed by using ImageMagick instead, however).
I'm now faced with doing this for a third time, on a potentially larger scale of users. I already plan on using ImageMagick to do some post processing to the image after the upload. I'd love to keep the restrictions on image uploads small as possible and possibly even retain every photo that someone uploads.
There will be times when hundreds of user's photo uploads will be displayed on the screen as a thumbnail at once. Storing these in a database and pulling them for each one and displaying via PHP doesn't seem like a good way to go, but throwing all images in to a single directory doesn't either.
What is your recommendation in this situation? Do you go with one of the options above or do you have a different solution? | > Storing these in a database and pulling them for each one and displaying via PHP doesn't seem like a good way to go, but throwing all images in to a single directory doesn't either.
You can take a hybrid approach.
Store the images in a heirarchy of folders (according to whatever scheme you determine to be appropriate for your application). Store the full path to each image in your database.
In a background job, have thumbnails of the images produced (say with ImageMagick) whose filenames slightly differ from the images themselves (eg: add 'thumb-' on the front) but which are stored alongside the real images. You can have a field in the database for each image which means "My thumbnail is ready, so please include me in galleries".
When you get a request for a gallery, slice and dice the group of images using database fields, then produce a piece of HTML which refers to the appropriate thumbnail and image paths.
---
**Edit:**
What Aaron F says is important when you need to handle a very large number of requests. Partitioning of the image / sql data is a good road to scalability. You'll need to look at access patterns in your application to determine where the partition points lie. Something you can do even sooner is to cache the generated HTML for the galleries in order to reduce SQL load. | The two examples you cite don't clarify the most important part: partitioning.
e.g. if stored in a database, do the images reside entirely in one table, on one database server? Or is the table partitoned across several servers/clusters?
e.g. if stored in a directory, do all the images reside on one hard drive? Or do images map to separate [RAID] drives, based on the first letter in the user's login name?
A good partitioning scheme is needed for scalability.
As far as displaying thumbnails in bulk, you'll probably want some precomputation here. i.e. create the thumbnails (perhaps via an ayschronous job, kicked off just after the image is uploaded) and stage them on a dedicated server. This is how Youtube does image snapshots of uploaded videos. | Recommended architecture for handling user image uploads | [
"",
"php",
"web-applications",
"upload",
"photo",
""
] |
I have 3 build machines. One running on windows 2000, one with XP SP3 and one with 64bit Windows Server 2008.
And I have a native C++ project to build (I'm building with visual studio 2005 SP1).
My goal is to build "exactly" the same dll's using these build machines.
By exactly I mean bit by bit (except build timestamp of course).
With win2k and winxp I'm getting identical dll's. But they differ from dll built with win2008 server.
I've managed to get almost identical dll's, but there are some differences. After disassembling the files I found out that function order is not the same (3 functions are in different order).
Does anyone know what could be the reason for that?
And a side question:
In vcbuild.exe I've found a switch /ORDER. Which takes function order file as input. Anyone knows how that file should look like? | You might think that compiling is purely deterministic (identical inputs give identical output, every time) but this need not be the case. For example, consider the optimiser - this is going to need some memory to work in, probably more for higher optimisation methods. If on one machine a memory allocation fails (because the machine has less memory) then the compiler could omit that specific optimisation, resulting in different code being emitted.
There are a lot of similar situations, so you may be putting a lot of effort into something that is not doable. Why do you need the DLLs to be bitwise identical, anyway? | Do you run the same version of the chain tool (compiler, linker, ...), included 32/64 bits difference? | Identical build on different systems | [
"",
"c++",
"dll",
"visual-studio-2005",
"compiler-construction",
"linker",
""
] |
In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, and then have it function as two separate apps with separate databases, etc.
To clarify, consider the following: hypothetically speaking, I would like to have a single, generic news\_content app, containing all the relevant models, views, url structure and templatetags, which I could then include and extend where necessary as many times as I like into a single project.
It breaks down as follows:
```
news_content/
templatetags/
__init__.py
news_content.py
__init__.py
models.py (defines generic models - news_item, category, etc.)
views.py (generic views for news, archiving, etc.)
urls.py
admin.py
```
Is there a way to include this app multiple times in a project under various names? I feel like it should be obvious and I'm just not thinking clearly about it. Does anybody have any experience with this?
I'd appreciate any advice people can give. Thank you. | What's the actual difference between blogs and news? Perhaps that difference ought to be part of the blog/news app and you include it just once.
If you have a blog page with blog entries and a news page with news entries and the only difference is a field in the database (kind\_of\_item = "blog" vs. kind\_of\_item = "news") then perhaps have you have this.
urls.py
```
(r'^/(?P<kind>blog)/$', 'view.stuff'),
(r'^/(?P<kind>news)/$', 'view.stuff'),
```
views.py
```
def stuff( request, kind ):
content= news_blog.objects.filter( kind=kind )
return render_to_response( kind+"_page", { 'content': content } )
```
Perhaps you don't need the same app twice, but need to extend the app to handle both use cases. | In this case you could create the common piece of code as a Python module instead of a whole new application.
Then for each instance you would like to use it, create an app and import the bits from that module. | Reusing a Django app within a single project | [
"",
"python",
"django",
""
] |
For instance... if i have a method that performs some asynchronous operation and i want to notify/call some sort of callback once it's done, would i use delegate?
I can't seem to get my head round how that would work. Can anyone point me in the right direction?
I was looking at something like....
```
public class ContentContext
{
public delegate void SuccessCallback(Dictionary<String, String> content);
public void DoSomeAsyncOpertaion(SuccessCallback successCallback)
{
//do something and then fire the callback
}
}
```
But something about that smells funny. Still a beginner with this c# stuff so forgive my ignorance ;)
Cheers
J | That looks fine to me. Though you could save yourself the delegate declaration and just use Action<>
I believe the [official pattern](http://msdn.microsoft.com/en-us/library/2e08f6yc(loband).aspx) is to use [IAsyncResult](http://msdn.microsoft.com/en-us/library/system.iasyncresult(loband).aspx), so I'd recommend that if you were developing a frameowrk. | It's ok but the callback will be called on the same thread as the asynchronous operation.
If this is an issue, get some informations about Threads in .Net, [SynchronizationContext](http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx), BackgroundWorder... | Is it right to use a delegate as a callback after some asynchronous operation? | [
"",
"c#",
"delegates",
""
] |
I'm working in VS2008 on a C# WinForms app. By default when clicking on a column header in a DataGridView it sorts that column Ascending, you can then click on the column header again to sort it Descending.
I am trying to reverse this, so the initial click sorts Descending then the second click sorts Ascending and I haven't been able to figure out how to do this. Does anyone know?
Thanks | You can set the HeaderCell SortGlyphDirection to Ascending, and then the next click will give you the descending order. The default is none.
```
dataGridView1.Sort(Column1, ListSortDirection.Ascending);
this.Column1.HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending;
``` | ```
foreach (DataGridViewColumn column in DataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Programmatic;
}
```
and
```
private void DataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
var column = DataGridView1.Columns[e.ColumnIndex];
if (column.SortMode != DataGridViewColumnSortMode.Programmatic)
return;
var sortGlyph = column.HeaderCell.SortGlyphDirection;
switch (sortGlyph)
{
case SortOrder.None:
case SortOrder.Ascending:
DataGridView1.Sort(column, ListSortDirection.Descending);
column.HeaderCell.SortGlyphDirection = SortOrder.Descending;
break;
case SortOrder.Descending:
DataGridView1.Sort(column, ListSortDirection.Ascending);
column.HeaderCell.SortGlyphDirection = SortOrder.Ascending;
break;
}
}
``` | DataGridViewColumn initial sort direction | [
"",
"c#",
"winforms",
"datagridview",
"sortdirection",
""
] |
In my c# windows application whenever I open my solution in visual studio 2008, than "MyApplication.vshost.exe" is always visible at window task manager--> Process tab.
When i tried to kill that, it again reappear at Process tab.
I am not getting for what vshost.exe created? and why its not getting removed from task manager?
How can we remove it? | You can read more about [vshost.exe on MSDN](http://msdn.microsoft.com/en-us/library/ms185331(VS.80).aspx).
> The hosting process is a feature in Visual Studio 2005 that improves debugging performance, enables partial trust debugging, and enables design time expression evaluation. The hosting process files contain vshost in the file name and are placed in the output folder of your project. | The vshost.exe feature was introduced with VS2005.
The purpose of it is mostly to make debugging launch quicker - basically there's already a process with the framework running, just ready to load your application as soon as you want it to.
See [this MSDN article](http://msdn.microsoft.com/en-us/library/ms242202.aspx) and [this blog post](http://blogs.msdn.com/dtemp/archive/2004/08/17/215764.aspx) for more information.
You can stop the \*.vshost.exe from spawning by -
Right clicking `MyProject` -> `Properties` -> `Debug` tab, and unchecking the `Enable the Visual Studio hosting process` checkbox. | C# window application: "MyApplication.vshost.exe" Continuous coming at task manager | [
"",
"c#",
".net",
""
] |
Here's my question for today. I'm building (for fun) a simple templating engine. The basic idea is that I have a tag like this {blog:content} and I break it in a method and a action. The problem is when I want to call a static variable dynamically, I get the following error .
```
Parse error: parse error, expecting `','' or `';''
```
And the code:
```
$class = 'Blog';
$action = 'content';
echo $class::$template[$action];
```
$template is a public static variable(array) inside my class, and is the one I want to retreive. | What about [`get_class_vars`](https://www.php.net/manual/en/function.get-class-vars.php) ?
```
class Blog {
public static $template = array('content' => 'doodle');
}
Blog::$template['content'] = 'bubble';
$class = 'Blog';
$action = 'content';
$values = get_class_vars($class);
echo $values['template'][$action];
```
Will output 'bubble' | You may want to save a reference to the static array first.
```
class Test
{
public static $foo = array('x' => 'y');
}
$class = 'Test';
$action = 'x';
$arr = &$class::$foo;
echo $arr[$action];
```
Sorry for all the editing ...
**EDIT**
```
echo $class::$foo[$action];
```
Seems to work just fine in PHP 5.3. Ahh, "[Dynamic access to static methods is now possible](http://ch2.php.net/manual/en/migration53.new-features.php)" was added in PHP 5.3 | Dynamically call a static variable (array) | [
"",
"php",
"class",
"static",
"model",
"methods",
""
] |
I am trying to find a good algorihtm that would detect corners in a image in a mobile phone. There are multiple algorithms to do that I am not sure which one will perform better in a memory and processor limited environment.
Specifically I am trying to find a sudoku grid in a picture taken using the camera of the phone. I am using C# and could not find any libraries that has basic image processing features. I implemented a Sobel filter to do edge detection and that is where I stand.
To make it clear the question is does anybody have any suggestions to use a specific algorithm or a library? | I wouldn't say "corner detection" by itself is a very good way to do this. Take a step back and think about a photo of a sodoku grid, there are probably lots of assumptions you can make to simplify things.
For example, a sodoku grid always looks exactly the same:
* White square
* 9 x 9 regular grid
[treating the image in the HSV colour space](http://answers.google.com/answers/threadview?id=68501) will allow you to look for high lightness areas (white-ish colours), RGB is a bit pants for most image-processing techniques.
[thresholding the image](http://en.wikipedia.org/wiki/Thresholding_(image_processing)) should then reduce noise
[Adjusting the image histogram](http://homepages.inf.ed.ac.uk/rbf/HIPR2/histgram.htm) first may also give you better results as it will probably whiten the grid (depends on the image though).
Then all you have to do is find a square. Because you know the grid is regular within it, you can divide the pixels up accordingly and OCR the squares with a number in.
:D | Since you are looking for a regular 9x9 grid consider the [Hough transform](http://en.wikipedia.org/wiki/Hough_transform). One way is to run an edge detector first, find all straight lines using the original Hough transform, and then try to figure out which of them form a grid. Or maybe you can come up with a clever way to parametrize the whole grid. | Corner detection algorithm for mobile | [
"",
"c#",
"image-processing",
"computer-vision",
""
] |
We are building a web App in PHP that should be able to receive SMS messages and store the information contained in it in database.
Which methods have you used? Which service providers are out there that can assist? | There are [AQL](http://www.aql.com/site/sms-php.php), [Intellisoftware](http://www.intellisoftware.co.uk/sms-gateway/php-sdk/) and the most well known of most gateways [Clickatell](http://www.clickatell.com/developers.php) all of which either provide PHP samples or simple interfaces (such as Soap, XML etc). When you receive an SMS message, most systems either call your server (i.e. via Soap/XML with the full message to a URL you provide, or with a message id which you can then query their server to get the full message details: some also provide "by email" notifications if needed).
I did use one quite succesfully a few years ago, but it doesn't seem to be around anymore.
See also [[Receive SMS messages by web application](https://stackoverflow.com/questions/526046/receive-sms-messages-by-web-application)](https://stackoverflow.com/questions/526046/receive-sms-messages-by-web-application). | you can try this: [integration code from SMSIntegra](http://www.smsintegra.com/) | How can i receive SMS through my web application? | [
"",
"php",
"sms",
""
] |
Currently, in my php script, after an user logged in, i stored session\_login = 1. But I have a problem. I have a habit in using firefox, multi-tab (i believe most people and all today web browsers app have multi-tab function). I closed the tab that has the session, but I didnt closed the browser. After few hours, I come back on the same page that require me to login, but it doesn't. It does not require me to login again(I think thats called "Session"). Is there anyway to logout the user if he close the tab instead close the browser??
I have 1 solution right now, time-idle kick out. But, I have very limited knowledge in date/time thing in php, so this would be the last option. I wanted to know, is there anything else i can do, beside using time-idle? | PHP has an easy way to set how long a session will last before it times out:
```
session_set_cookie_params(3600); // make it expire after 1 hour
```
Just pass it the number of seconds you want the session to last (in the example, 1 hour = 60 minutes = 3600 seconds).
<https://www.php.net/manual/en/function.session-set-cookie-params.php> | A session cookie is only cleared from the browser when the browser session is closed (i.e. when the browser is closed): hence the name. If you want the session to be cleared shortly after the tab is closed you could set a very short expiry time on the cookie (around 5 minutes) and store the same in the database. Then have a javascript function on the web page calling a file from your server every minute: this file then "refreshes" the cookie/database entry for the next five minutes. If they then leave your site for more than five minutes, then the session is invalidated.
You could also add a Javascript "onunload" function which detects if they have closed the webpage or gone to another page: you could add a hook on this to call a "destroycookie" function - however, you'll have to check that they haven't just gone to another page on your site and don't actually have two pages from your site open in two tabs. | How to log out an user in php? | [
"",
"php",
"session",
"logout",
""
] |
I'm writing a quick server app for something so don't really want to write a full GUI. However the problem is that the main part of the server, however the console window will only allow input or output at a time.
Many games ive played that have a console in them (usually needs activating in some way or another) they solved this problem by separating the input and output, such that the bottom line is dedicated to entering input commands, while the rest is used for output like a normal console window.
Is it possible to do something like that with a minimal amount of work (ie without having to write my own console window from scratch), and in a cross platform way? Ideally id like to still use the normal command prompt somehow for the case where the server is running on a system without all the GUI stuff installed, although I guess a simple GUI client that could connect with the server would be fine as well.
By cross platform I mean Windows and Linux support is required. Although if I went the client GUI route id also require Mac on top of that. | Sounds like you should have a look at **curses**
[ncurses](http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/intro.html#WHATIS)
[pdcurses](http://pdcurses.sourceforge.net/) | GUI builders these days are very easy. You might find that clicking together a gui is easier than solving this the way you want.
I'm a bit uncertain about the cross-platform part. Could you narrow it down a bit and specify which platforms you have in mind?
If you are considering Linux (which in itself is cross-platform, at least to some extent), then I'd take a look at ncurses. | C++ Real time console app, simultaneous input and output | [
"",
"c++",
"cross-platform",
"console-application",
"io",
""
] |
I'm just starting my journey into OOP - and I'm currently trying to roll my own MVC - purely for learning purposes. I'm working through a tutorial in the Apress PHP-Objects Patterns Practice book. I've created a registry singleton object using the private \_\_construct/\_\_clone technique:
```
class Registry
{
private static $instance;
private $values = array();
private function __construct(){}
private function __clone(){}
public static function getInstance(){
if( !isset( self::$instance ) ){
self::$instance = new Registry();
}
return self::$instance;
}
public function get( $key ) {
if ( isset( $this->values[$key] ) ) {
return $this->values[$key];
}
return null;
}
public function set( $key, $val ) {
$this->values[$key] = $val;
}
}
```
I get an instance of this object directly i.e:
```
Registry::getInstance();
```
However, (following the syntax in the tutorial) - if I try and access the public methods using the '->' method - e.g:
```
Registry->setVal('page',$page);
```
I get a parse error. I can only access the methods using the scope resolution operator - i.e '::'.
I'm assuming this is because the object wrapper has not been *instantiated* - but I just want to verify/discuss this issue with y'all... | `Registry::getInstance()` returns a (in fact the only) instance of the class `Registry`. It has the same return value as `new Registry()`, just that there will can only one instance in your whole application. These are your possibilities to access the methods:
```
// #1
$registry = Registry::getInstance();
$registry->set($key, $value);
// #2
Registry::getInstance()->set($key, $value);
```
Another trick:
Map `get()` and `set()` to their magic methods.
```
public function __set($key, $value)
{
return $this->set($key, $value);
}
public function __get($key)
{
return $this->get($key);
}
```
So you can use either `Registry::getInstance()->set($key, $value);` or `Registry::getInstance()->$key = $value;` | You need to call setVal() on an instance, not the class itself, so you could do this:
```
Registry::getInstance()->set('page', $page);
``` | Accessing singleton methods in PHP | [
"",
"php",
"oop",
"static",
"singleton",
"methods",
""
] |
Here's what's going on. I'm opening a file on FTP that exists using a WebClient. The file exists and the function has worked in the past, but now for some reason throws an exception. (System.Net.WebException: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).). The funny thing is, the script still opens the file and does what it's supposed to. Has anyone ever heard of anything like this?
```
WebClient downloadRequest = new WebClient();
downloadRequest.Credentials = new NetworkCredential(pusername, ppassword);
byte[] downloadBytes = downloadRequest.DownloadData(purl);
```
Here's the stack trace:
```
[WebException: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +287
System.Net.WebClient.DownloadData(Uri address) +106
System.Net.WebClient.DownloadData(String address) +29
ftp_connect.copyFile(String purl, String pusername, String ppassword, String pubordev) in d:\wwwdev\test\ftp\ftpconnect.aspx.cs:112
ftp_connect.copyFolder(String purl, String pusername, String ppassword, String pubordev) in d:\wwwdev\test\ftp\ftpconnect.aspx.cs:160
ftp_connect.Page_Load(Object sender, EventArgs e) in d:\wwwdev\test\ftp\ftpconnect.aspx.cs:93
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
``` | It turns out that I was calling a function which called the function I was trying to get to.
So, the solution I guess was to look at the stack. Should have done that first. | Presumably the file is there from a previous successful run? | Exception on C# - but program still works | [
"",
"c#",
".net",
"exception",
"webclient",
""
] |
I plan to use it with JavaScript to crop an image to fit the entire window.
**Edit**: I'll be using a 3rd party component that only accepts the aspect ratio in the format like: `4:3`, `16:9`. | I gather you're looking for an usable aspect ratio `integer:integer` solution like `16:9` rather than a `float:1` solution like `1.77778:1`.
If so, what you need to do is find the greatest common divisor (GCD) and divide both values by that. The GCD is the highest number that evenly divides both numbers. So the GCD for 6 and 10 is 2, the GCD for 44 and 99 is 11.
For example, a 1024x768 monitor has a GCD of 256. When you divide both values by that you get 4x3 or 4:3.
A (recursive) GCD algorithm:
```
function gcd (a,b):
if b == 0:
return a
return gcd (b, a mod b)
```
In C:
```
static int gcd (int a, int b) {
return (b == 0) ? a : gcd (b, a%b);
}
int main(void) {
printf ("gcd(1024,768) = %d\n",gcd(1024,768));
}
```
And here's some complete HTML/Javascript which shows one way to detect the screen size and calculate the aspect ratio from that. This works in FF3, I'm unsure what support other browsers have for `screen.width` and `screen.height`.
```
<html><body>
<script type="text/javascript">
function gcd (a, b) {
return (b == 0) ? a : gcd (b, a%b);
}
var w = screen.width;
var h = screen.height;
var r = gcd (w, h);
document.write ("<pre>");
document.write ("Dimensions = ", w, " x ", h, "<br>");
document.write ("Gcd = ", r, "<br>");
document.write ("Aspect = ", w/r, ":", h/r);
document.write ("</pre>");
</script>
</body></html>
```
It outputs (on my weird wide-screen monitor):
```
Dimensions = 1680 x 1050
Gcd = 210
Aspect = 8:5
```
Others that I tested this on:
```
Dimensions = 1280 x 1024
Gcd = 256
Aspect = 5:4
Dimensions = 1152 x 960
Gcd = 192
Aspect = 6:5
Dimensions = 1280 x 960
Gcd = 320
Aspect = 4:3
Dimensions = 1920 x 1080
Gcd = 120
Aspect = 16:9
```
I wish I had that last one at home but, no, it's a work machine unfortunately.
What you do if you find out the aspect ratio is not supported by your graphic resize tool is another matter. I suspect the best bet there would be to add letter-boxing lines (like the ones you get at the top and bottom of your old TV when you're watching a wide-screen movie on it). I'd add them at the top/bottom or the sides (whichever one results in the least number of letter-boxing lines) until the image meets the requirements.
One thing you may want to consider is the quality of a picture that's been changed from 16:9 to 5:4 - I still remember the incredibly tall, thin cowboys I used to watch in my youth on television before letter-boxing was introduced. You may be better off having one different image per aspect ratio and just resize the correct one for the actual screen dimensions before sending it down the wire. | ```
aspectRatio = width / height
```
if that is what you're after. You can then multiply it by one of the dimensions of the target space to find out the other (that maintains the ratio)
e.g.
```
widthT = heightT * aspectRatio
heightT = widthT / aspectRatio
``` | What's the algorithm to calculate aspect ratio? | [
"",
"javascript",
"algorithm",
"aspect-ratio",
"crop",
""
] |
Coming from a different development environment (Java, mostly) I'm trying to make analogies to habits I'm used to.
I'm working with a C++ project in Visual Studio 2005, the project takes ~10 minutes to compile after changes. It seems odd that if I make a small syntactical error, I need to wait a few good minutes to get a feedback on that from the compiler, when running the entire project build.
Eclipse gave me the habit that if I make some small change I will immediately get a compiler error with an underline showing the error. Seems reasonable enough that VS should be able to do this.
[](https://i.stack.imgur.com/eT0Do.png)
Is this something I can enable in VS or do I need an external plug-in for this? | The feature you are asking for will be available in Visual Studio 2010. [Here is a detailed link of the feature details](http://blogs.msdn.com/vcblog/archive/2009/06/01/c-gets-squiggles.aspx) that will be available.
For now, as others have suggested, you can use Visual Assist which can help a little bit.
These are called Squiggles BTW. | You can try the following:
* install a plugin like Visual Assist: it will notify you about most of the errors;
* if you want to check yourself, use Ctrl-F7 to compile the file you are currently editing - in such case, you will not need to wait for all project to compile. If you are editing a header file, compile one of the .cpp files it is included in. | C++ error detection in Visual Studio 2005 | [
"",
"c++",
"visual-studio",
"visual-c++-2005",
""
] |
What must I put into `distutils.cfg` to prevent easy\_install from ever installing a zipped egg? The compression is a nice thought, but I like to be able to grep through and debug that code.
I pulled in some dependencies with `python setup.py develop .` A closer look reveals that also accepts the --always-unzip flag. It would just be nice to set that as default. | the option is zip-ok, so put the following in your distutils.cfg:
```
[easy_install]
# i don't like having zipped files.
zip_ok = 0
``` | I doubt there is a setting in distutils.cfg for this, as easy\_install is not a part of distutils. But run easy\_install like this:
```
easy_install --always-unzip
```
and it should solve the problem. | How do I forbid easy_install from zipping eggs? | [
"",
"python",
"setuptools",
"easy-install",
""
] |
I know it is not a programming related,
I am in PHP Development for last 2 years, now will it be possible(how hard) or advisale for me to shift to .net Development.
any help ?
Thanks in Advance, | [Ramp Up](http://msdn.microsoft.com/en-us/rampup/default.aspx) is a microsoft site that has training based upon prior experience. For example, you can take training for php developers, where they use php constructs as analogies for things you are learning. | It's certainly possible. I've worked in both, and while I find things about both platforms that I prefer over the other, I don't think it's terribly hard to learn one system having already worked on the other.
For me it was no harder than any other time I've learned a new language. | PHP developer to .net development | [
"",
".net",
"php",
""
] |
Can the semaphore be lower than 0? I mean, say I have a semaphore with N=3 and I call "down" 4 times, then N will remain 0 but one process will be blocked?
And same the other way, if in the beginning I call up, can N be higher than 3? Because as I see it, if N can be higher than 3 if in the beginning I call up couple of times, then later on I could call down more times than I can, thus putting more processes in the critical section then the semaphore allows me.
If someone would clarify it a bit for me I will much appreciate.
Greg | Calling down when it's 0 should not work. Calling up when it's 3 does work. (I am thinking of Java).
Let me add some more. Many people think of locks like (binary) semaphores (ie - N = 1, so the value of the semaphore is either 0 (held) or 1 (not held)). But this is not quite right. A lock has a notion of "ownership" so it may be "reentrant". That means that a thread that holds a lock, is allowed to call lock() again (effectively moving the count from 0 to -1), because the thread already holds the lock and is allowed to "reenter" it. Locks can also be non reentrant. A lock holder is expected to call unlock() the same number of times as lock().
Semaphores have no notion of ownership, so they cannot be reentrant, although as many permits as are available may be acquired. That means a thread needs to block when it encounters a value of 0, until someone increments the semaphore.
Also, in what I have seen (which is Java), you can increment the semaphore greater than N, and that also sort of has to do with ownership: a Semaphore has no notion of ownership so anybody can give it more permits. Unlike a thread, where whenever a thread calls unlock() without holding a lock, that is an error. (In java it will throw an exception).
Hope this way of thinking about it helps. | (Using the terminology from java.util.concurrent.Semaphore given the Java tag. Some of these details are implementation-specific. I suspect your "down" is the Java semaphore's `acquire()` method, and your "up" is `release()`.)
Yes, your last call to `acquire()` will block until another thread calls `release()` or your thread is interrupted.
Yes, you can call `release()` more times, then down more times - at least with `java.util.concurrent.Semaphore`.
Some other implementations of a semaphore may have an idea of a "maximum" number of permits, and a call to release beyond that maximum would fail. The Java `Semaphore` class allows a reverse situation, where a semaphore can start off with a negative number of permits, and all `acquire()` calls will fail until there have been enough `release()` calls. Once the number of permits has become non-negative, it will never become negative again. | How does semaphore work? | [
"",
"java",
"multithreading",
"computer-science",
"semaphore",
""
] |
I've built an analytical data visualization engine for Canvas and have been requested to add tooltip-like hover over data elements to display detailed metrics for the data point under the cursor.
For simple bar & Gaant charts, tree graphs and node maps with simple square areas or specific points of interest, I was able to implement this by overlaying absolutely-positioned DIVs with :hover attributes, but there are some more complicated visualizations such as pie charts and a traffic flow rendering which has hundreds of separate areas defined by bezeir curves.
Is is possible to somehow attach an overlay, or trigger an event when the user mouses over a specific closed path?
Each area for which hover needs to be specified is defined as follows:
```
context.beginPath();
context.moveTo(segmentRight, prevTop);
context.bezierCurveTo(segmentRight, prevTop, segmentLeft, thisTop, segmentLeft, thisTop);
context.lineTo(segmentLeft, thisBottom);
context.bezierCurveTo(segmentLeft, thisBottom, segmentRight, prevBottom, segmentRight, prevBottom);
/*
* ...define additional segments...
*/
// <dream> Ideally I would like to attach to events on each path:
context.setMouseover(function(){/*Show hover content*/});
// </dream>
context.closePath();
```
Binding to an object like this is almost trivial to implement in Flash or Silverlight, since but the current Canvas implementation has the advantage of directly using our existing Javascript API and integrating with other Ajax elements, we are hoping to avoid putting Flash into the mix.
Any ideas? | You could handle the mousemove event and get the x,y coordinates from the event. Then you'll probably have to iterate over all your paths to test if the point is over the path. I had a [similar problem](https://stackoverflow.com/questions/1148424/registering-clicks-on-an-element-that-is-under-another-element) that might have some code you could use.
Looping over things in this way can be slow, especially on IE. One way you could potentially speed it up - and this is a hack, but it would be quite effective - would be to change the color that each path is drawn with so that it is not noticeable by humans but so that each path is drawn in a different color. Have a table to look up colors to paths and just look up the color of the pixel under the mouse. | **Shadow Canvas**
The best method I have seen elsewhere for mouseover detection is to repeat the part of your drawing that you want to detect onto a hidden, cleared canvas. Then store the ImageData object. You can then check the ImageData array for the pixel of interest and return true if the alpha value is greater than 0.
```
// slow part
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(100,100,canvas.width-100,canvas.height-100);
var pixels = ctx.getImageData(0,0,canvas.width,canvas.height).data;
// fast part
var idx = 4 * (mouse_x + mouse_y * canvas.width) + 3;
if (pixels[idx]) { // alpha > 0
...
}
```
**Advantages**
* You can detect anything you want since you're just repeating the context methods. This works with PNG alpha, crazy compound shapes, text, etc.
* If your image is fairly static, then you only need to do this one time per area of interest.
* The "mask" is slow, but looking up the pixel is dirt cheap. So the "fast part" is great for mouseover detection.
**Disadvantages**
* This is a memory hog. Each mask is W\*H\*4 values. If you have a small canvas area or few areas to mask, it's not that bad. Use chrome's task manager to monitor memory usage.
* There is currently a known issue with getImageData in Chrome and Firefox. The results are not garbage collected right away if you nullify the variable, so if you do this too frequently, you will see memory rise rapidly. It does eventually get garbage collected and it shouldn't crash the browser, but it can be taxing on machines with small amounts of RAM.
**A Hack to Save Memory**
Rather than storing the whole ImageData array, we can just remember which pixels have alpha values. It saves a great deal of memory, but adds a loop to the mask process.
```
var mask = {};
var len = pixels.length;
for (var i=3;i<len;i+=4) if ( pixels[i] ) mask[i] = 1;
// this works the same way as the other method
var idx = 4 * (mouse_x + mouse_y * canvas.width) + 3;
if (mask[idx]) {
...
}
``` | Detect mouseover of certain points within an HTML canvas? | [
"",
"javascript",
"canvas",
""
] |
I am currently using `jconsole` to monitor performance metrics of my Java application and would like to **script** this **data acquisition**.
Is there a way to retrieve these VM metrics (heap memory usage, thread count, CPU usage etc.) to `STDOUT`?
The data in `top -p PID -b -n 1` doesn't quite cut it.
Thanks | `jconsole` just provides a wrapper around the JMX MBeans that are in the platform `MBeanServer`.
You can write a program to connect to your VM using the [Attach API](http://java.sun.com/javase/6/docs/jdk/api/attach/spec/index.html) which would then query the MBeans.
Or you can expose the platform `MBeanServer` over RMI and query the MBeans that way.
See the [java.lang.management](http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html) package for more info | Maybe [jvmtop](https://github.com/patric-r/jvmtop) is worth a look.
It's a command-line tool which provides a **live-view** for several metrics.
### Example output of the VM overview mode:
```
JvmTop 0.4.1 amd64 8 cpus, Linux 2.6.32-27, load avg 0.12
http://code.google.com/p/jvmtop
PID MAIN-CLASS HPCUR HPMAX NHCUR NHMAX CPU GC VM USERNAME #T DL
3370 rapperSimpleApp 165m 455m 109m 176m 0.12% 0.00% S6U37 web 21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager 11m 28m 23m 130m 0.00% 0.00% S6U37 web 31
19187 m.jvmtop.JvmTop 20m 3544m 13m 130m 0.93% 0.47% S6U37 web 20
16733 artup.Bootstrap 159m 455m 166m 304m 0.12% 0.00% S6U37 web 46
``` | Can jconsole data be retrieved from the command line? | [
"",
"java",
"performance",
"command-line",
"monitoring",
"jconsole",
""
] |
All I need is a way to query an NTP Server using C# to get the Date Time of the NTP Server returned as either a `string` or as a `DateTime`.
How is this possible in its simplest form? | Since the old accepted answer got deleted (It was a link to a Google code search results that no longer exist), I figured I could answer this question for future reference :
```
public static DateTime GetNetworkTime()
{
//default Windows time server
const string ntpServer = "time.windows.com";
// NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.Connect(ipEndPoint);
//Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
}
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime.ToLocalTime();
}
// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
return (uint) (((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
```
**Note:** You will have to add the following namespaces
```
using System.Net;
using System.Net.Sockets;
``` | This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)
```
public static DateTime GetNetworkTime()
{
const string ntpServer = "pool.ntp.org";
var ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
``` | How to Query an NTP Server using C#? | [
"",
"c#",
"datetime",
"ntp",
""
] |
I'd like to know the correct / best way to handle concurrency with an Axis2 webservice.
Eg, given this code:
```
public class MyServiceDelegate
{
@Resource
UserWebService service; // Injected by spring
public CustomerDTO getCustomer()
{
String sessionString = getSessionStringFromCookies();
service.setJSESSIONID(sessionString);
CustomerDTO customer = service.getCustomerFromSessionID();
}
}
```
Note that in the above that UserWebService is a 3rd party API. The service requires that when making calls, we pass a cookie with the `JSESSIONID` of an authenticated session.
Am I correct in assuming that this statement is not threadsafe? IE., given two threads, is it possible for the following to occur?
* ThreadA : `service.setJSESSIONID("threadA")`
* ThreadB : `service.setJSESSIONID("threadB")`
* ThreadA : `service.getCustomerFromSessionID // service.sesionID == "threadB"`
If so, what's the most appropriate way to handle this situation? Should I use a resource pool for service? Or should I declare service as synchronized?
```
public CustomerDTO getCustomer()
{
synchronized( service ) {
service.setJSESSIONID(sessionString);
CustomerDTO customer = service.getCustomerFromSessionID();
}
}
```
Or, is there another, more appropriate way to handle this problem? | Would each thread have its own Delegate object and hence its own UserWebService service?
In the simple case, if delegates are created on the stack the threads would be independent.
If the cost of creation is high, have a pool of the delegate objects. Taking one from teh pool is comparativley cheap. You need to be very careful with housekeeping, but effectively this is what is done with database connections. Some environments have utility classes for managing such pooling - tends to be preferable to rolling your own. | Is UserWebService one of your classes? If so, I think I'd change the method signature to:
```
public CustomerDTO getCustomer()
{
CustomerDTO customer = service.getCustomerFromSessionID(sessionString);
}
```
And not have your UserWebService maintain state, that way it will be inherently thread-safe | Java concurrency : Making webservice access threadsafe | [
"",
"java",
"web-services",
"thread-safety",
""
] |
```
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
``` | The `BoxLayout` is easy - the argument (`Y_AXIS`) to the `BoxLayout` constructor belongs to the `BoxLayout` class so you need to specify that. There may well be another `Y_AXIS` value which would be the wrong one to use.
This is the basis of encapsulation.
With regards to the `panel` double-mention, I can't be sure. But it seems plausible that the panel needs to be told what its layout manager is *and* the layout manager needs to know which panel it's applied to (since it needs to know the contents of the panel in order to lay them out intelligently). | The `panel` arguement to `BoxLayout` is somewhat confusing. You need to specify the target that the `BoxLayout` instance is attached to. Further, in many methods based on the `LayoutManager2` Interface, `BoxLayout` requires the `panel` to be passed in and it performs a check that you have passed in the right one.
The Y\_AXIS is a class variable that is one of two legal int values for the orientation of the `BoxLayout`. You could just pass in the value 0, but using the constant is much better. | Why say panel and boxlayout twice? | [
"",
"java",
"swing",
"layout",
""
] |
I'm aiming to create a feature in my latest project preferably using PHP. When each user signs up they are going to input their postcode. Then hopefully I will be converting this to lat/long using Open Street Map.
Anyway, I want to be able to find out other users located near the current user.
I have seen a lot of people using the Haversine formula, however this would mean that the user queried every other user's details to work out the distance. I could cache this but its soon going to become outdated as new users sign up.
What sort of effect would running the following query have on my system?
```
sql = "SELECT zipcode, ( 3959 * acos( cos( radians( {$coords['latitude']} ) )
* cos( radians( latitude ) ) * cos( radians( longitude )
- radians( {$coords['longitude']} ) )
+ sin( radians( {$coords['latitude']} ) ) * sin( radians( latitude ) ) ) )
AS distance FROM zipcodes HAVING distance <= {$radius} ORDER BY distance";
```
That's pulled from someone's blog.
I don't have any figures for the signup rate or the amount of users as it's still in development.
I would appreciate any feedback or other methods that I could use to find matching users within a specific radius. | There are GIS and Spatial Extensions to mySql in version 4.1, see [here](http://dev.mysql.com/tech-resources/articles/4.1/gis-with-mysql.html). From the description you will find, that it is used for problems like you have here:
> A GIS (geographic information system)
> stores and looks up objects which have
> one or more spatial attributes, such
> as size and position, and is used to
> process such objects. A simple example
> would be a system that stores
> addresses in a town using geographic
> coordinates. If this rather static
> data was then combined with other
> information, such as the location of a
> taxi-cab, then this data could be used
> to find the closest cab to a certain
> location.
It adds several things to MySql like:
* Spacial keys and the POINT type:
CREATE TABLE address (
address CHAR(80) NOT NULL,
address\_loc **POINT** NOT NULL,
PRIMARY KEY(address),
**SPATIAL** KEY(address\_loc)
);
* Conversion routines
INSERT INTO address VALUES('Foobar street 12', **GeomFromText('POINT(2671 2500)')**);
* GIS calculation functions
SELECT
c.cabdriver,
ROUND(**GLength(LineStringFromWKB(LineString(AsBinary(c.cab\_loc),
AsBinary(a.address\_loc))))**)
AS distance
FROM cab c, address a
ORDER BY distance ASC LIMIT 1;
(Examples taken from link above) | The problem can be greatly simplified if you are willing to loosen the definition of "within a certain radius" to not specifically be a circle. If you simplify to a "square", you can find all location within the "radius" with 2 simple "between" clauses (one for lat one for long). eg:
```
SELECT * FROM location WHERE
lat BETWEEN (my_lat - radius) AND (my_lat + radius)
AND long BETWEEN (my_long - radius) AND (my_long + radius);
```
Of course, this could be used to select a subset of your locations before using a more accurate method to calculate the actual distance to them. | Best method for working out locations within a radius of starting point | [
"",
"php",
"mysql",
"postal-code",
"haversine",
""
] |
I have a dilemma going on here. I need to use a session to navigate records in a foreach loop.
```
foreach($key as $val)
{
echo '<tr><td><a href="'.$key.'">$val</a></td></tr>';
}
```
Ok, the $key in this equasion is my database key and when the user clicks the link, it will take them to the next page. This "next page" parses the data and places it into a query string for the URL. I don't like the way it's working with the query string and want to use a session to handle the $key instead but I dont know how to make that work for a hyperlink. Can someone please give me a hand?
Thanks
The whole thing in a nutshell is that I don't want to get the key off the URL. It has nothing to do with security but I want to put that key into a hidden field so that I can parse it later. | This will hide the key and store it in session. You could also use numeric indexes instead of the md5 and salt if you dont like the long md5 strings, or the uniqid function.
```
//store this value in a config file
$salt = 'somelongsecretstring';
foreach($key as $val)
{
$md5 = md5($salt . $key);
$_SESSION['keys'][$md5] = $key;
echo '<tr><td><a href="?key='.$md5.'">$val</a></td></tr>';
}
```
At the next page:
```
$md5 = $_GET['key'];
if (!isset($_SESSION['keys'][$md5])) {
//key doesnt exists, redirect to previous page and display error.
}
$key = $_SESSION['keys'][$md5];
``` | That's no good idea. The URI (or URL if you want) identifies a UNIQUE resource. A short example:
**Good** (unique)
`http://example.org/page/1` => GET key = 1
`http://example.org/page/2` => GET key = 2
**Bad** (not unique)
`http://example.org/page` w/ session key = 1
`http://example.org/page` w/ session key = 2 | PHP - how to use a session in place of the GET var | [
"",
"php",
""
] |
I have the following code
```
DirectoryInfo taskDirectory = new DirectoryInfo(this.taskDirectoryPath);
FileInfo[] taskFiles = taskDirectory.GetFiles("*" + blah + "*.xml");
```
I would like to sort the list by filename.
How is this done, as quickly and easily as possible using .net v2. | Call Array.Sort, passing in a comparison delegate:
```
Array.Sort(taskFiles, delegate(FileInfo f1, FileInfo f2) {
return f1.Name.CompareTo(f2.Name);
});
```
In C# 3 this becomes slightly simpler:
```
Array.Sort(taskFiles, (f1, f2) => f1.Name.CompareTo(f2.Name));
```
Or you can use a `StringComparer` if you want to use a case-insensitive sort order:
```
Array.Sort(taskFiles,
(x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name));
```
(or use `string.Compare(x.Name, y.Name, true)`, or any of the many other ways of comparing strings :) | ```
Array.Sort(taskFiles, delegate (FileInfo x, FileInfo y) {
return string.Compare(x.Name,y.Name);
});
``` | How to sort an array of FileInfo[] | [
"",
"c#",
".net-2.0",
".net",
""
] |
I have been refactoring the codebase of the project that I am currently on so that classes/interfaces which are not useful beyond the confines of the assembly should be declared as internal (rather than public). But I've run into a problem with the following code:
```
internal interface IFirstInterface
{
...
}
internal interface ISecondInterface
{
IFirstInterface First{ get; }
...
}
public class Implementer : ISecondInterface
{
public IFirstInterface First {get; private set;}
...
}
```
My questions:
1. Why do members of internal interfaces have to be publicly implemented? If you implement the interface on an internal class, shouldn't the implemented members be internal? This is not a big issue since the interface members won't be publicly accessible anyway, given the class is internal. It just seems counter intuitive.
2. The main problem is with the scenario above since I cannot have a public getter for IFirstInterface since it is purportedly an internal interface i.e. I get the following error from the compiler:
> Inconsistent accessibility: property
> type 'IFirstInterface' is less
> accessible than property
> 'Implementer.First'
Is there any way around this?
**Note**: I realise that there is probably little value in this refactoring exercise but I thought it would be a good way for me to understand more deeply the implications of the internal modifier. | Just to note - the code you've actually provided *does* compile, because `Implementer` is an internal class. The problem comes when `Implementer` is public.
The way round this is to use explicit interface implementation:
```
public class Implementer : ISecondInferface
{
private IFirstInterface first;
IFirstInterface ISecondInterface.First { get { return first; } }
}
```
You can't have the setter in there, because you're explicitly implementing the interface which doesn't define the setter. You *could* do this as an alternative:
```
public class Implementer : ISecondInterface
{
internal IFirstInterface First { get; private set; }
IFirstInterface ISecondInterface.First { get { return First; } }
}
```
It's unfortunate that internal interfaces have public members - it does complicate things like this. It would be strange for a public interface to have an internal member (what would it be internal to - the implementer or the declarer?) but for internal interfaces it makes a lot more sense. | > Why do members of internal interfaces have to be publicly implemented?
When you define an interface, you do not define access level for the members, since all interface members are `public`. Even if the interface as such is `internal`, the members are still considered `public`. When you make an implicit implementation of such a member the signature must match, so it needs to be `public`.
Regarding exposing the getter, I would suggest making an *explicit* implementation of the interface instead, and creating an `internal` property to expose the value:
```
internal IFirstInterface First { get; private set; }
IFirstInterface ISecondInterface.First
{
get { return this.First; }
}
``` | How do I implement members of internal interfaces | [
"",
"c#",
"interface",
"internal",
""
] |
I am looking for some decent ADO.NET helper utility class to allow me to query an ado.net datasource. I am not looking for anything too fancy, but it has to support transactions. Is there anything out there?
P.S. I know the data access block will do that but I was looking for something a bit more independent to other components. like a simple library or something | If its just a light wrapper Why not just wrap the commands yourself?
eg:
```
/// <summary>
/// Executes a stored procedure or query, returns the number of rows effected.
/// </summary>
/// <param name="commandText"></param>
/// <param name="commandType"></param>
/// <param name="sqlParameters"></param>
/// <param name="sqlTransaction"></param>
/// <returns></returns>
public static int ExecuteQuery(string commandText, CommandType commandType, List<SqlParameter> sqlParameters, SqlTransaction sqlTransaction)
{
if (sqlTransaction == null)
{
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString()))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandType = commandType;
sqlCommand.CommandText = commandText;
if (sqlParameters != null)
{
foreach (SqlParameter sqlParameter in sqlParameters)
{
sqlCommand.Parameters.Add(sqlParameter);
}
}
return sqlCommand.ExecuteNonQuery();
}
}
}
else
{
SqlCommand sqlCommand = new SqlCommand(commandText, sqlTransaction.Connection, sqlTransaction);
sqlCommand.CommandType = commandType;
foreach (SqlParameter sqlParameter in sqlParameters)
{
sqlCommand.Parameters.Add(sqlParameter);
}
return sqlCommand.ExecuteNonQuery();
}
}
``` | It depends on your definitions of "nothing fancy" and "simple", but [BLToolkit](http://bltoolkit.net/) does a pretty decent job of abstracting away boilerplate ADO.NET code that you don't really want to write manually. For instance,
```
public abstract class PersonAccessor : DataAccessor<Person>
{
[SqlQuery("SELECT * FROM Person WHERE PersonID = @id")]
public abstract Person GetPersonByID(int @id);
}
Person person = DataAccessor.CreateInstance<PersonAccessor>.
GetPersonByID(2);
```
will fetch a `Person` object from the DB in just -- see that? -- 5-6 lines of code.
As for `DataSet`s, [here's](http://bltoolkit.net/Doc/Data/ExecuteDataSet.htm) how:
```
using (DbManager db = new DbManager())
{
DataSet ds = db
.SetCommand("SELECT * FROM Person")
.ExecuteDataSet();
Assert.AreNotEqual(0, ds.Tables[0].Rows.Count);
}
```
Adding parameters is as simple as calling a method on the `DbManager`.
And you shouldn't be really afraid of ORMs. | Any decent ADO.NET Helper utils out there? | [
"",
"c#",
".net",
"ado.net",
""
] |
First, please note, that I am interested in how something like this would work, and am not intending to build it for a client etc, as I'm sure there may already be open source implementations.
How do the algorithms work which detect plagiarism in uploaded text? Does it use regex to send all words to an index, strip out known words like 'the', 'a', etc and then see how many words are the same in different essays? Does it them have a magic number of identical words which flag it as a possible duplicate? Does it use [levenshtein()](https://www.php.net/manual/en/function.levenshtein.php)?
My language of choice is PHP.
**UPDATE**
I'm thinking of not checking for plagiarism globally, but more say in 30 uploaded essays from a class. In case students have gotten together on a strictly one person assignment.
Here is an online site that claims to do so: <http://www.plagiarism.org/> | Good plagiarism detection will apply heuristics based on the type of document (e.g. an essay or program code in a specific language).
However, you can also apply a general solution. Have a look at the [Normalized Compression Distance](http://www.complearn.org/ncd.html) (NCD). Obviously you cannot exactly calculate a text's [Kolmogorov complexity](http://en.wikipedia.org/wiki/Kolmogorov_complexity), but you can approach it be simply compressing the text.
A smaller NCD indicates that two texts are more similar. Some compression
algorithms will give better results than others. Luckily PHP provides support
for [several](https://www.php.net/manual/en/refs.compression.php) compression algorithms, so you can have your NCD-driven plagiarism
detection code running in no-time. Below I'll give example code which uses
[Zlib](http://en.wikipedia.org/wiki/Zlib):
PHP:
```
function ncd($x, $y) {
$cx = strlen(gzcompress($x));
$cy = strlen(gzcompress($y));
return (strlen(gzcompress($x . $y)) - min($cx, $cy)) / max($cx, $cy);
}
print(ncd('this is a test', 'this was a test'));
print(ncd('this is a test', 'this text is completely different'));
```
Python:
```
>>> from zlib import compress as c
>>> def ncd(x, y):
... cx, cy = len(c(x)), len(c(y))
... return (len(c(x + y)) - min(cx, cy)) / max(cx, cy)
...
>>> ncd('this is a test', 'this was a test')
0.30434782608695654
>>> ncd('this is a test', 'this text is completely different')
0.74358974358974361
```
Note that for larger texts (read: actual files) the results will be much more
pronounced. Give it a try and report your experiences! | I think that this problem is complicated, and doesn't have one best solution.
You can detect exact duplication of words at the whole document level (ie someone downloads an entire essay from the web) all the way down to the phrase level. Doing this at the document level is pretty easy - the most trivial solution would take the checksum of each document submitted and compare it against a list of checksums of known documents. After that you could try to detect plagiarism of ideas, or find sentences that were copied directly then changed slightly in order to throw off software like this.
To get something that works at the phrase level you might need to get more sophisticated if want any level of efficiency. For example, you could look for differences in style of writing between paragraphs, and focus your attention to paragraphs that feel "out of place" compared to the rest of a paper.
There are lots of papers on this subject out there, so I suspect there is no one perfect solution yet. For example, these 2 papers give introductions to some of the general issues with this kind of software,and have plenty of references that you could dig deeper into if you'd like.
<http://ir.shef.ac.uk/cloughie/papers/pas_plagiarism.pdf>
<http://proceedings.informingscience.org/InSITE2007/IISITv4p601-614Dreh383.pdf> | How would you code an anti plagiarism site? | [
"",
"php",
"theory",
""
] |
I was just wondering how I use Ant to build my web applications that I have written in PHP? I've googled around a bit and I have seen that it is possible but there are not any examples of the basic idea or any advanced use for them. Can any of you help me out?
Thanks! | While Ant itself is written in java, you can use it to build any kind of applications you want. Here's a [basic tutorial](http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html) and a [full manual](http://ant.apache.org/manual/index.html). Beyond that, you need to clarify what is it you want to do to get a more precise answer here.
**Update** (based on question clarifications):
Copying / moving files / folders is easy via Ant. Look through the "Hello World" tutorial I've linked above and Familiarize yourself with [FileSet](http://ant.apache.org/manual/Types/fileset.html) concept and [Copy](http://ant.apache.org/manual/Tasks/copy.html), [Mkdir](http://ant.apache.org/manual/Tasks/mkdir.html) and [Move](http://ant.apache.org/manual/Tasks/move.html) tasks to get started. Here's [another tutorial](http://techtracer.com/2007/04/16/the-great-ant-tutorial-a-great-jump-start/) that shows how to set up a basic build (ignore java-specific stuff like javac/war).
Making changes to the database is an entirely different subject. If you have 'alter' scripts ready, you can use Ant's [Exec](http://ant.apache.org/manual/Tasks/exec.html) task to invoke your DB's command-line client to run those scripts (though I probably wouldn't do it in production). If you want to use Ant to **track** those changes, then you're looking at the wrong tool. [Liquibase](http://www.liquibase.org/) can be used to do that and it seems to be getting a lot of traction lately. It's quite like Ant in the sense that it's written in Java but can be used in any environment. I'm no PHP expert so I wouldn't know if there's something more PHP-geared available. | This is definitely possible. If you are looking for a pure php solution [phing](http://phing.info/trac/) might be what you want. Also note that there's usually no reasons to build PHP scripts. They should 'just work'. | build PHP with ant scripts | [
"",
"php",
"ant",
"build",
""
] |
I'd like to check if there is anything to return given a number to check against, and if that query returns no entries, increase the number until an entry is reached and display that entry. Currently, the code looks like this :
```
SELECT *
FROM news
WHERE DATEDIFF(day, date, getdate() ) <= #url.d#
ORDER BY date desc
```
where #url.d# is an integer being passed through (say 31). If that returns no results, I'd like to increase the number stored in #url.d# by 1 until an entry is found. | This kind of incremental querying is just not efficient. You'll get better results by saying - "I'll never need more than 100 results so give me these" :
```
SELECT top 100 *
FROM news
ORDER BY date desc
```
Then filtering further on the client side if you want only a particular day's items (such as the items with a common date as the first item in the result).
Or, you could transform your multiple query request into a two query request:
```
DECLARE
@theDate datetime,
@theDate2 datetime
SET @theDate = (SELECT Max(date) FROM news)
--trim the time off of @theDate
SET @theDate = DateAdd(dd, DateDiff(dd, 0, @theDate), 0)
SET @theDate2 = DateAdd(dd, 1, @theDate)
SELECT *
FROM news
WHERE @theDate <= date AND date < @theDate2
ORDER BY date desc
``` | If you wanted the one row:
```
SELECT t.*
FROM NEWS t
WHERE t.id = (SELECT MAX(n.id)
FROM NEWS n
WHERE n.date BETWEEN DATEADD(day, -:url.d, getDate()) AND getDate())
```
It might not be obvious that the DATEADD is using a negative in order to go back however many number of days desired.
If you wanted all the rows in that date:
```
SELECT t.*
FROM NEWS t
WHERE t.date BETWEEN DATEADD(day, -:url.d, getDate()) AND getDate())
``` | SQL Checking for NULL and incrementals | [
"",
"sql",
"null",
"increment",
""
] |
I have a class "Employee", this has an IList<> of "TypeOfWork".
```
public class Employee
{
public virtual IList<TypeOfWork> TypeOfWorks { get; set; }
}
public class TypeOfWork
{
public virtual Customer Customer { get; set; }
public virtual Guid Id { get; set; }
public virtual string Name{ get; set; }
public virtual bool IsActive{ get; set; }
}
```
before saving, I'd lile to know if "typeofwid" (a Guid) is already in the "TypeOfWorks" collection.
I tried this :
```
var res = from p in employee.TypeOfWorks
where p.Id == new Guid("11111111-1111-1111-1111-111111111111")
select p ;
```
and tried this :
```
bool res = employee.TypeOfWorks.Where(f => f.Id == new Guid("11111111-1111-1111-1111-111111111111")).Count() != 0;
```
in the "Immediate Window" of Visual Studio but I receive the error : *Expression cannot contain query expressions* in both case
Do you have an idea ?
Thanks, | Just what the error says. You can't use LINQ queries in the Immediate Window because they require compilation of lambda functions. Try the first line in your actual code, where it can be compiled. :)
Also, to get this all done in one line, you can use the LINQ "Any" operator, like so:
```
if( ! employee.TypeOfWorks.Any(tow => tow.Id == theNewGUID) )
//save logic for TypeOfWork containing theNewGUID
``` | How about this:
```
Guid guid = Guid.NewGuid("11111111-1111-1111-1111-111111111111");
var res = from p in employee.TypeOfWorks
where p.Id == guid
select p ;
```
The problem is constructing the guid - otherwise the linq queries should work | Check if a value is in a collection with LINQ | [
"",
"c#",
"linq",
"collections",
"lambda",
""
] |
I am getting this error when I retrieve a row with a null DataTime field:
> 'srRow.Closed\_Date' threw an exception of type 'System.Data.StrongTypingException'
How do I properly handle these? | You can check for a null value in that column before retrieving the value.
```
if (!srRow.IsClosed_DateNull())
{
myDate = srRow.Closed_Date;
}
``` | There's a reference [here](http://msdn.microsoft.com/en-us/library/ms242030(VS.80).aspx).
or possibly, can you modify your query to ensure the results are not null by using the IsNull operator?
```
Select (IsNull, SomeDateField, GetDate())
``` | How do I handle a DBNull DateTime field coming from the SQL Server? | [
"",
"c#",
"datetime",
"null",
"dbnull",
""
] |
I have the following code but I am getting an exception that a smtp host is not defined. If I am running this and testing on my local machine from visual studio, what do I need to do to be able to send email from my machine. Do I have to turn on some Windows service?
```
private void SendMailToAdminToApprove(string email_, string name_)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("address@domain.com", "Person's Name");
msg.To.Add(new MailAddress("a@gmail.com", "Adam"));
msg.Subject = "Message Subject";
msg.Body = "Mail body content";
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
try
{
SmtpClient c = new SmtpClient();
c.Send(msg);
}
catch (Exception ex)
{
Console.Write("T");
}
}
``` | You need to set the SMTP host to point to an actual SMTP server. One option is to run the SMTP service on your own machine, but you could also point to your ISP's server.
*edit*
As pcampbell and Skeolan mentioned, the actual value should go into app.config. I'm not sure if localhost would be an exception: it would depend on whether you want the option of not running a local server. | You'll need to specify the SMTP host here:
```
string smtpHost = "localhost";
//or go to your config file
smtpHost = ConfigurationManager.AppSettings["MySmtpHost"].ToString();
SmtpClient c = new SmtpClient(smtpHost);
``` | Sending email using .NET | [
"",
"c#",
"email",
"smtp",
""
] |
Are there any downsides to using a JavaScript "class" with this pattern?
```
var FooClass = function()
{
var private = "a private variable";
this.public = "a public variable";
var privatefn = function() { ... };
this.publicfn = function() { ... };
};
var foo = new FooClass();
foo.public = "bar";
foo.publicfn();
``` | What you're doing in your example isn't the "class" pattern people think of in JS -- typically people are thinking of the more "normal" class model of Java/C#/C++/etc which can be faked with libraries.
Instead your example is actually fairly normal and good JS design, but for completeness i'll discuss behaviour differences you'll see between the private and public "members" you have
```
var private = "a private variable";
this.public = "a public variable";
```
Accessing `private` from within any of your functions will be quite a lot faster than accessing `public` because the location of `private` can be determined reasonably well just with a static lookup by the JS engine. Attempts to access `public` require a lookup, most modern JS engines perform a degree of lookup caching, but it is still more expensive than a simple scoped var access.
```
var privatefn = function() { ... };
this.publicfn = function() { ... };
```
The same lookup rules apply to these functions as with the above variable accesses, the only real difference (in your example) is that if your functions are called, say `privatefn()` vs `this.publicfn()`, `privatefn` will always get the global object for `this`. But also if someone does
```
f = foo.publicfn;
f();
```
Then the call to `f` will have the global object as `this` *but* it will be able to modify the `private` variable.
The more normal way to do public functions however (which resolves the detached public function modifying private members issue) is to put public functions on the prototype, eg.
```
Foo.prototype.publicfn = function() { ... }
```
Which forces public functions to not modify private information -- there are some times where this isn't an option, but it's good practice as it also reduces memory use slightly, take:
```
function Foo1() {
this.f = function(){ return "foo" };
}
```
vs
```
function Foo2() {
}
Foo2.prototype.f = function(){ return "foo" };
```
In `Foo1` you have a copy of the function object for every instance of `Foo1` (not all the emory, just the object, eg. `new Foo1().f !== new Foo2().f`) whereas in `Foo2` there is only a single function object. | That's good so far, but there's another access level you've left out.
`this.publicfn` is really a priveleged method as it has access to private members and functions.
To add methods which are public but not priveleged, modify the prototype as follows:
```
FooClass.prototype.reallypublicfn = function () { ... };
```
note that this method does not have access to private members of FooClass but it is accessible through any instance of FooClass.
Another way of accomplishing this is returning these methods from the constructor
```
var FooClass = function()
{
var private = "a private variable";
this.public = "a public variable";
var privatefn = function() { ... };
this.publicfn = function() { ... };
return {
reallypublicfn: function () { ...}
}
};
var foo = new FooClass();
foo.public = "bar";
foo.publicfn();
```
Basically, these methods of data hiding help you adhere to traditional OOP techniques. Generally speaking, improving data-hiding and encapsulation in your classes is a good thing. Ensuring low coupling makes it much easier to change things down the road, so publicly exposing as little as possible is really to your benefit.
See <https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript> for a simple overview and <http://www.crockford.com/javascript/private.html> for details on how to accomplish these things. | JavaScript "classes" | [
"",
"javascript",
"performance",
"class",
""
] |
I am working on porting code from JAVA to C#, and part of the JAVA code uses tokenizer - but it is my understanding that the resulting array from the stringtokenizer in Java will also have the separators (in this case +, -, /, \*, (, )) as tokens. I have attempted to use the C# Split() function, but it seems to eliminate the separators themselves. In the end, this will parse a string and run it as a calculation. I have done a lot of research, and have not found any references on the topic.
Does anyone know how to get the actual separators, in the order they were encountered, to be in the split array?
Code for token-izing:
```
public CalcLexer(String s)
{
char[] seps = {'\t','\n','\r','+','-','*','/','(',')'};
tokens = s.Split(seps);
advance();
}
```
Testing:
```
static void Main(string[] args)
{
CalcLexer myCalc = new CalcLexer("24+3");
Console.ReadLine();
}
```
The "24+3" would result in the following output: "24", "3" I am looking for an output of "24", "+", "3"
In the nature of full disclosure, this project is part of a class assignment, and uses the following complete source code:
<http://www.webber-labs.com/mpl/source%20code/Chapter%20Seventeen/CalcParser.java.txt>
<http://www.webber-labs.com/mpl/source%20code/Chapter%20Seventeen/CalcLexer.java.txt> | You can use `Regex.Split` with zero-width assertions. For example, the following will split on `+-*/`:
```
Regex.Split(str, @"(?=[-+*/])|(?<=[-+*/])");
```
Effectively this says, "split at this point if it is followed by, or preceded by, any of `-+*/`. The matched string itself will be zero-length, so you won't lose any part of the input string. | This produces your output:
```
string s = "24+3";
string seps = @"(\t)|(\n)|(\+)|(-)|(\*)|(/)|(\()|(\))";
string[] tokens = System.Text.RegularExpressions.Regex.Split(s, seps);
foreach (string token in tokens)
Console.WriteLine(token);
``` | C# Tokenizer - keeping the separators | [
"",
"c#",
"stringtokenizer",
""
] |
I'm using the Amazon AIMS API to upload a an inventory file and I'm having an issue with the cURL call to upload the file. The documentation is very limited, so there is no example code that helps out in this.
This is what I have so far of the cURL call:
```
// $FILENAME is filename of the CSV file being uploaded:
$inventory = fopen($FILENAME, 'r') or die("Can't open file!");
echo $inventory;
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_INFILE, $inventory);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filename));
curl_setopt($ch, CUROPT_PUT, TRUE);
$response = curl_exec($ch);
curl_close($ch);
```
I've try putting $inventory into the CURLOPT\_POSTFIELDS and not having an INFILE, but I get the same error.
On the XML response, I'm getting "`NO_FILE_ATTACHED`" so the obvious issue is getting the file to be attached to the XML call.
I also tried uploading as the first responder said using the Example #2 on the curl\_setopt page on php.net.
For that, I used the following code:
```
$data = array('@/tmp/amazon_export.csv');
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
```
I got the same `NO_FILE_ATTACHED` response back.
Any ideas? | This works for me:
```
$hCurl = curl_init();
curl_setopt($hCurl, CURLOPT_PUT, true);
curl_setopt($hCurl, CURLOPT_HEADER, true);
curl_setopt($hCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($hCurl, CURLOPT_CONNECTTIMEOUT, CURL_TIMEOUT_SECS);
curl_setopt($hCurl, CURLOPT_URL, "$oMessage->url/att/$fid");
curl_setopt($hCurl, CURLOPT_HTTPHEADER, $aCurlHeaders);
// TODO it could be possible that fopen() would return an invalid handle or not work altogether. Should handle that
$fp = fopen ($finfo['tmp_name'], "r");
curl_setopt($hCurl, CURLOPT_INFILE, $fp);
curl_setopt($hCurl, CURLOPT_INFILESIZE, $finfo['size']);
$sResp = curl_exec($hCurl);
``` | You are combining `PUT` and `POST` in a single curl operation, which will not work. Refer to [example #2](http://php.net/manual/function.curl-setopt.php#function.curl-setopt.examples) of the [curl\_setopt](http://php.net/curl_setopt) manual page for an example on how to upload a file using POST. | How can I attach a file with a PHP cURL XML Call | [
"",
"php",
"xml",
"curl",
""
] |
**Can you store an Array in Memcache?**
I would like to store;
1. A user ID number
2. A user's photo URL
3. A users name
Together as an array, someone told me you could and then someone told me you couldn't
Which is it? | Yes.
```
Memcache::set('someKey', array(
'user_id' => 1,
'url' => 'http://',
'name' => 'Dave'
));
```
Please see the [documentation](https://www.php.net/manual/en/ref.memcache.php) for very detailed examples. | max storage size of an item in memcache is 1,048,576 Bytes (1MB), serializing an array does take a bit of space.
if you were to structure your array as simply as:
```
array(
[0] => 1,
[1] => 2,
[2] => 3
)
```
key being auto generated and value being the user id.
a serialized array of 5000 users numbered 1-5000 using this structure has a string length of 67792 characters, 50000 users produces an array of 777794 characters.
numbering 100000 to 150000 produces a serialized string of 838917 characters.
so at 50k users (as referenced in your previous question), you will likely be under the 1MB limit. if you have a local cache though (APC, etc...), use that instead, or if for any reason do NOT need all the IDs at once, I would highly suggest splitting up the results or simply using the DB.
also think about the data structure you are storing in memcached. If you are using the cache simply to give you a list of primary keys to lookup, do you need the other data? | Can you store a PHP Array in Memcache? | [
"",
"php",
"memcached",
""
] |
I have a javascript event handler in one of my SSI files that hides a bunch of elements that may or may not appear on the page that calls the SSI file. As a result, the handler goes smoothly until it cannot find the element I'm asking it to hide and then stops before completing whatever may be left to hide. So, how can I get JavaScript to not get hung up on whether or not the element is on the page and just get through the handler?
Many thanks.
Mike | Depends on how you're getting the element. If you're not using a JS library then you could do something like this:
```
/* handler begin code */
var el = document.getElementById('myElement');
if (el) {
//do work
}
/* handler end code */
```
Its easier if you use something like jQuery, where you can select the element and then even if it doesn't exist any operations on the selected set will not throw an exception
```
//this will work even if myElement doesn't exist - no exceptions will be thrown
$("#myElement").hide();
``` | Some code would be nice to answer this properly, but what about this:
```
if (element) {
element.hide();
}
``` | How can I ask JavaScript to hide an element ONLY IF it can be found? | [
"",
"javascript",
"html",
"css",
""
] |
I have a CRC class written in VB.NET. I need it in C#. I used an online converter to get me started, but I am getting some errors.
```
byte[] buffer = new byte[BUFFER_SIZE];
iLookup = (crc32Result & 0xff) ^ buffer(i);
```
On that line, the compiler gives me this error:
> **Compiler Error Message:** CS0118: 'buffer' is a 'variable' but is used like a 'method'
Any ideas how I could fix this?
Thanks! | Change `buffer(i)` to `buffer[i]` | Change buffer(i) to buffer[i] as VB array descriptors are () and C# array descriptors are []. | Need some help converting VB.NET code to C# | [
"",
"c#",
"code-conversion",
""
] |
I have just won 1 Telerik Premium Collection for .NET Developer with subscription (lucky me!) and was wondering whether the OpenAccess ORM is worth learning? Has anyone thrown away their open source variant and are now using the Telerik ORM tools instead?
Are there any benefits from using the Telerik ORM tools instead of an open source variant?
Any thought suggestions? | I'm a happy telerik customer for more than 5 years. I used their ORM only in one solution and never used an open source ORM.
Throw away the existing one?
NO - if you have no problems and the thing does what it should do I wouldn't change.
That has nothing to do with quality or other aspects of telerik ORM.
It's just a matter of fact that using a new product means to learn new things, solve some solved things again in a different way and so on.
BUT - if you have problems (or must make compromises) with your current product it's sure worth to give it a try.
Without knowing other ORMs I have one clear point why I would try telerik ORM.
It's their (telerik's) outstanding support.
None of my other vendors offers / does what telerik does.
Simply take a look at their forums <http://www.telerik.com/community/forums.aspx> and you'll see what I mean.
You have a problem - they solve it; and that with very fast response times.
And that's a point you should think about when making a decision about ORM (or any other kind of product). | We recently started using Telerik's SiteFinity product for a client website. It is a very good, developer-oriented tool for creating a web content system without the size or expense of SharePoint or something similar.
We also went with a Cloud solution as Telerik's ORM supports Azure, so thus so does SiteFinity - which uses OpenAccess (ORM) to communicate with its database.
I was very impressed with the speed and flexibility of it all, being my first Cloud (Azure) development project. Telerik's customer support and personal attention is beyond reproach. I have been using Telerik products for years and was not surprised how well it worked.
Two days before the site was to go live everything bombed with a very inexplicable .Net error. As it turns out Microsoft announced they were upgrading their Azure SQL servers starting July, 2011: "This upgrade is also significant in that it represents a big first step towards providing a common base and feature set between the cloud SQL Azure service and our upcoming release of SQL Server Code Name 'Denali'."
(<http://blogs.msdn.com/b/windowsazure/archive/2011/07/13/announcing-sql-azure-july-2011-service-release.aspx>)
By its very nature, Cloud servers are upgraded and moved around behind the scenes so you don't have to mess with it. OpenAccess failed to take this into account however, and when our SQL Azure server group was upgraded OpenAccess failed to recognize its version and bombed.
Telerik, of course, was very quick about releasing a patch - but it still took them a few days. We couldn't wait that long, unfortunately, having already lost quite a bit of time just trying to figure out what was going on. The practical result was that I got to work nonstop for two days with no sleep to move the whole thing into a regular .Net solution with Entity Framework 4 as the ORM.
So to answer the question: Is Telerik ORM worth learning and / or better than an open source solution? I agree with the above statement that if you already have an open source solution, it is working well, has good performance, and is intuitive to develop against - absolutely stick with that.
The value of open source is the community that supports it and your ability to make changes to the underlying system if need be. Had my project been based on an open source ORM, I could have changed the code to default to the most recent version of SQL if it finds it is working with a version higher, and problem solved - sleep had.
The value of a product like OpenAccess ORM is that it is in competition with other products, open source or otherwise, and it has to: Perform Well, be customer oriented, have a manual (very important), and be easier than doing it yourself or learn an open source system that may or may not be very intuitive.
Throw in that Telerik's support is top notch, and I would say you could do worse - as long as you are willing to give up some control and have to wait for upgrades / patches to handle things like I described above. | Is Telerik openaccess ORM worth learning? | [
"",
"c#",
"orm",
"telerik",
""
] |
I have recently been running into many different areas of SQL Server that I normally don't mess with. One of them that has me confused is the area of Logins and Users. Seems like it should be a pretty simple topic...
It appears that each login can only have 1 user and each user can only have 1 login.
A login can be associated to multiple tables thus associating that user to many tables.
So my question is why even have a login and a user? they seem to be pretty much one in the same. What are the differences, or what is it that I seem to be missing? | A "Login" grants the principal entry into the SERVER.
A "User" grants a login entry into a single DATABASE.
One "Login" can be associated with many users (one per database).
Each of the above objects can have permissions granted to it at its own level. See the following articles for an explanation of each
* [Principals](http://msdn.microsoft.com/en-us/library/ms181127(SQL.90).aspx)
* [Database Users](http://msdn.microsoft.com/en-us/library/ms190928(SQL.90).aspx) | One reason to have both is so that authentication can be done by the database server, but authorization can be scoped to the database. That way, if you move your database to another server, you can always remap the user-login relationship on the database server, but your database doesn't have to change. | Difference between a User and a Login in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I am trying to implement "IF record EXISTS THEN UPDATE ELSE INSERT" in mysql. Specifically, I have to figure out how to do that with Doctrine ORM.
One solution using native MySql is to use "ON DUPLICATE KEY UPDATE". This is unfortunately not supported in Doctrine.
Another semi solution is to use "REPLACE INTO" syntax. Doctrine supports this, however REPLACE doesn't UPDATE records, instead it drops the record and creates a new one (with a new auto increment id.) Because of this, it's a bad solution if you depend on auto-increment ids as I do.
The table I'm trying to operate on is INNODB, so I have looked into transactions, but I don't fully understand if the same rules apply inside of transactions as apply outside of them.
Can I say "IF(INSERT IGNORE INTO table `critical_id` = $id) THEN exit ELSE (UPDATE table SET `field` = 'new\_value')" inside of a transaction?
If I can't say something like that, is there any solution to this problem? | Either find a way to make "ON DUPLICATE KEY UPDATE" work, or switch to using two statements: first SELECT to find any existing rows, then UPDATE or INSERT as necessary.
That's pretty much your only option, short of building a stored proc that does the above work for you. | "Insert or update" is called "Upsert". If you google "upsert mysql" you will find that there are only few solutions.
1. 2-step, Insert, then Update and variations
2. "ON DUPLICATE KEY UPDATE"
3. REPLACE
And maybe few more, but most of those are variations.
Using transactions your SQL would look like this:
```
UPDATE xxx SET (x1, x2) = (y1, y2) WHERE id = myid;
IF found THEN
RETURN;
END IF;
BEGIN
INSERT INTO xxx (x1, x2) VALUES (y1, y2);
RETURN;
EXCEPTION WHEN unique_violation THEN
--##Do nothing, or you can put this whole sql code
--##in a LOOP and it will loop over and try update again
END;
```
This code is stripped from one of my postgresql functions. I think InnoDB doesn't support this, but I might be wrong. | can you begin a mysql statement with "IF"? | [
"",
"php",
"mysql",
"orm",
"doctrine",
"conditional-statements",
""
] |
Recently i asked a [question](https://stackoverflow.com/questions/1195260/installing-django-with-modwsgi) regarding an error in apache/mod\_wsgi recognizing the python script directory.
The community kindly answered the question resulting in a successful installation. Now I have a different error, the server daemon (well, technically is a windows service, I say tomato you say...) doesn't find any of the models, here's the full traceback:
Environment:
```
Request Method: GET
Request URL: `http://localhost/polls/`
Django Version: 1.0.2 final
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.polls']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
```
Template error:
In template c:\users\marcos\documents\djangotemplates\polls\poll`_`list.html, error at line 1
Caught an exception while rendering: no such table: polls\_poll
```
1 : {% if object_list %}
2 : <ul>
3 : {% for poll in object_list %}
4 : <li> <a href="{{poll.id}}/">{{ poll.question }} </a> </li>
5 : {% endfor %}
6 : </ul>
7 : {% else %}
8 : <p>No polls are available.</p>
9 : {% endif %}
10 :
```
Traceback:
```
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\views\generic\list_detail.py" in object_list
101. return HttpResponse(t.render(c), mimetype=mimetype)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
176. return self.nodelist.render(context)
File "C:\Python26\lib\site-packages\django\template\__init__.py" in render
768. bits.append(self.render_node(node, context))
File "C:\Python26\lib\site-packages\django\template\debug.py" in render_node
81. raise wrapped
```
```
Exception Type: TemplateSyntaxError at /polls/
Exception Value: Caught an exception while rendering: no such table: polls_poll
```
somewhere someone advice me to use **manage.py dbshell** and the script responded:
Error: You appear not to have the 'sqlite3' program installed or on your path.
But still the Django runserver runs the app perfectly. I don't see what changed in the environment to screw the web-app so hard. Please help! | You don't have a database. It's not clear why you don't have a sqlite3 driver. However, you don't have sqlite3 and you don't have a database.
1. Run manage.py syncdb build the database.
* Be sure to use the same `settings.py` as your production instance.
* Be sure your `settings.py` has the correct driver. You're using SQLite3, be sure that an absolute path name is used.
* Be sure to use the same `PYTHONPATH` and working directory as production to be sure that all modules are actually found
2. Run ordinary SQL to see that you actually built the database.
3. Run the Django `/admin` application to see what's in the database.
SQLite3 is included with Python. For it to be missing, your Python installation must be damaged or incomplete. Reinstall from scratch. | I solve the problem adding the sqlite3 binaries directory to the PYTHONPATH environment variable. | Error in Django running on Apache/mod_wsgi | [
"",
"python",
"django",
"apache",
"sqlite",
"mod-wsgi",
""
] |
Hi can I'm very new to windows forms. Here I want to maintain state (like session in web applications) in windows forms.
Actually i want to store user login details in session. But i think there is no concept of session in winforms. So what is the alternative method to handle this type of situation.
Regards,
Nagu | There is no concept of Session variables in windows forms. What you can do is:
1. Create a internal class that holds the User name and password and any other variables and enumerations needed across the application (Something like Common.cs). These can be accessed through public properties across the application.
2. Have a parameterized constructor for all the forms and send the user name and the password whenever you are showing the form. | ```
public class MyForm : Form
{
private string userName;
private string password;
}
```
Since windows forms are statefull (opposed to stateless for web forms), you can just use a field in your Form class. | How do I maintain user login details in a Winforms application? | [
"",
"c#",
"winforms",
""
] |
I'm trying to write an excel file from php, and I need that some cells to have date type; do you have any ideas which is the format code for that type of cell?
I'm using the code from <http://pizzaseo.com/php-excel-creator-class> to generate the excel files.
Thanks. | Your question is a little vague, and I know little about PHP, but I'm the maintainer of a similar Python package ... so here's an attempt to help:
Excel doesn't differentiate at the BIFF record level between numbers and dates. The only way that an XLS reader can tell whether a date was intended by the writer is to parse the "number format" that the writer associated (indirectly) with the cell in question.
I presume that you are using this Format function to set the num\_format of what the package calls a "format" (which includes not only "number format" but alignment, background, borders, ...):
```
function setNumFormat($num_format)
```
$num\_format should be an Excel "number format" (e.g. for a money amount you might use "$0.00"). For a date you just use whichever you prefer of the standard date formats Excel provides, or you could use a customised format like "yyyy-mm-dd hh:mm:ss" (handy when debugging).
Then you do:
```
worksheet->write($row, $col, $value, $format)
```
Where $format is as described above. For a date, $value should be a floating point day-number where 1900-03-01T00:00:00 is represented as day-number 61.0 and you should avoid earlier dates because ... [long rant omitted], and if there's a "datemode" or "1904" option available, ensure that you are using the (should be default) 0 or False or "no, thanks" option. | Here's the reference document for the Excel binary format from Microsoft, this gives you all the information regarding the various cell types:
[Microsoft Excel 97-2007 Binary File Format](https://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Excel97-2007BinaryFileFormat(xls)Specification.pdf) | Excel BIFF file format - cell type for date | [
"",
"php",
"excel",
""
] |
I have a class, and list of instances, that looks something like this (field names changed to protect the innocent/proprietary):
```
public class Bloat
{
public long timeInMilliseconds;
public long spaceInBytes;
public long costInPennies;
}
public class BloatProducer
{
final private List<Bloat> bloatList = new ArrayList<Bloat>();
final private Random random = new Random();
public void produceMoreBloat()
{
int n = bloatList.size();
Bloat previousBloat = (n == 0) ? new Bloat() : bloatList.get(n-1);
Bloat newBloat = new Bloat();
newBloat.timeInMilliseconds =
previousBloat.timeInMilliseconds + random.nextInt(10) + 1;
newBloat.spaceInBytes =
previousBloat.spaceInBytes + random.nextInt(10) + 1;
newBloat.costInPennies =
previousBloat.costInPennies + random.nextInt(10) + 1;
bloatList.add(newBloat);
}
/* other fields/methods */
public boolean testMonotonicity()
{
Bloat previousBloat = null;
for (Bloat thisBloat : bloatList)
{
if (previousBloat != null)
{
if ((previousBloat.timeInMilliseconds
>= thisBloat.timeInMilliseconds)
|| (previousBloat.spaceInBytes
>= thisBloat.spaceInBytes)
|| (previousBloat.costInPennies
>= thisBloat.costInPennies))
return false;
}
previousBloat = thisBloat;
}
return true;
}
BloatProducer bloatProducer;
```
The list `bloatList` is kept internally by `BloatProducer` and is maintained in such a way that it only appends new `Bloat` records, does not modify any of the old ones, and each of the fields is monotonically increasing, e.g. `bloatProducer.testMonotonicity()` would always return `true`.
I would like to use `Collections.binarySearch(list,key,comparator)` to search for the `Bloat` record by either the timeInMilliseconds, spaceInBytes, or costInPennies fields. (and if the number is between two records, I want to find the previous record)
What's the easiest way to write a series of 3 Comparator classes to get this to work? Do I have to use a key that is a Bloat object with dummy fields for the ones I'm not searching for? | You'll need to write a separate comparator for each field you want to compare on:
```
public class BloatTimeComparator implements Comparator<Bloat> {
public int compare(Bloat bloat1, Bloat bloat2) {
if (bloat1.timeInMilliseconds > bloat2.timeInMilliseconds) {
return 1;
} else if (bloat1.timeInMilliseconds < bloat2.timeInMilliseconds) {
return -1;
} else {
return 0;
}
}
}
```
And so on for each property in `Bloat` you want to compare on (you'll need to create a comparator class for each). Then use the Collections helper method:
```
Collections.binarySearch(bloatList, bloatObjectToFind,
new BloatTimeComparator());
```
From the [Java documentation](http://java.sun.com/javase/6/docs/api/) for the binarySearch method, the return value will be:
> the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
Which is the index you specified that you wanted. | You will need to have 3 separate `Comparator`s if you want to search by each of the 3 properties.
A cleaner option would be to have a generic `Comparator` which receives a parameter which tells it by which field to compare.
A basic generic comparator should look something like this:
```
public class BloatComparator implements Comparator<Bloat>
{
CompareByEnum field;
public BloatComparator(CompareByEnum field) {
this.field = field;
}
@Override
public int compare(Bloat arg0, Bloat arg1) {
if (this.field == CompareByEnum.TIME){
// compare by field time
}
else if (this.field == CompareByEnum.SPACE) {
// compare by field space
}
else {
// compare by field cost
}
}
}
``` | writing a Comparator for a compound object for binary searching | [
"",
"java",
"binary-search",
"comparator",
""
] |
I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm\_source=twitter&utm\_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this? | System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
```
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
```
This gives the output: <http://www.website.com/default.aspx>
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri *up to and including* the part I specify". This can be Scheme (just the http:// bit), Authority (the [www.website.com](http://www.website.com) part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller. | Here is a simple trick
```
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
``` | Truncating Query String & Returning Clean URL C# ASP.net | [
"",
"c#",
"asp.net",
"url",
"query-string",
"truncate",
""
] |
I've just started using Team Foundation Server and have added a new Solution that contains a project of type class library. I need to add a reference to the new class library project to an existing class library (dll) that we have created. What is the best way to do this? I've noticed that if I try to add it from the original location as an existing dll, it keeps the original location of the dll. I think what I want is to actually copy the dll to the new project, and add a reference to it locally - but I can't figure out how to do that. | Can you include both the old and new projects in the same solution? If so, you can reference the project directly (primary artifact) instead of the .dll output (secondary output). This 'just works' when you need to build multiple configurations, such as debug, release, etc. | Write a MSbuild/Nant script that build's and copies the dll to a common lib directory. Then reference the lib\foo.dll in 2nd project. Also create the build order. | Team Foundation Server - Add rereference to existing dll to a new class library project | [
"",
"c#",
"tfs",
""
] |
I have a report that tracks how long certain items have been in the database, and does so by tracking it over a series of age ranges (20-44, 45-60, 61-90, 91-180, 180+). I have the following query as the data source of the report:
```
SELECT DISTINCT Source.ItemName,
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) > 20) AS Total,
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 20 AND 44) AS BTWN_20_44,
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 45 AND 60) AS BTWN_45_60,
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 61 AND 90) AS BTWN_61_90,
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) BETWEEN 91 AND 180) AS BTWN_91_180,
Count(SELECT Source.DateAdded FROM Source WHERE Int(Date()-Source.DateAdded) > 180) AS GT_180
FROM Source
GROUP BY Source.ItemName;
```
This query works great, except if there aren't any entries a column. Instead of returning a count of 0, an empty value is returned.
How do I get Count() to return a 0 instead of empty? | Replace the `Count` statements with
```
Sum(Iif(DateDiff("d",DateAdded,Date())>=91,Iif(DateDiff("d",DateAdded,Date())<=180,'1','0'),'0')) AS BTWN_91_180,
```
I'm not a fan of the nested `Iif`s, but it doesn't look like there's any way around them, since `DateDiff` and `BETWEEN...AND` were not playing nicely.
To prune `ItemName`s without any added dates, the query block had to be enclosed in a larger query, since checking against a calculated field cannot be done from inside a query. The end result is this query:
```
SELECT *
FROM
(
SELECT DISTINCT Source.ItemName AS InvestmentManager,
Sum(Iif(DateDiff("d",DateAdded,Date())>=20,Iif(DateDiff("d",DateAdded,Date())<=44,'1','0'),'0')) AS BTWN_20_44,
Sum(Iif(DateDiff("d",DateAdded,Date())>=45,Iif(DateDiff("d",DateAdded,Date())<=60,'1','0'),'0')) AS BTWN_45_60,
Sum(Iif(DateDiff("d",DateAdded,Date())>=61,Iif(DateDiff("d",DateAdded,Date())<=90,'1','0'),'0')) AS BTWN_61_90,
Sum(Iif(DateDiff("d",DateAdded,Date())>=91,Iif(DateDiff("d",DateAdded,Date())<=180,'1','0'),'0')) AS BTWN_91_180,
Sum(Iif(DateDiff("d",DateAdded,Date())>180,'1','0')) AS GT_180,
Sum(Iif(DateDiff("d",DateAdded,Date())>=20,'1','0')) AS Total
FROM Source
WHERE CompleteState='FAILED'
GROUP BY ItemName
)
WHERE Total > 0;
``` | You can return
```
ISNULL(Count(......), 0)
```
and all should be fine - would be in MS SQL Server - but I just saw you're using Access. Since I don't know Access enough, I'm not sure this will work - can you try it?
OK - glad to see there's something similar in Access (if not exactly the same as in SQL Server).
Marc | Make a query Count() return 0 instead of empty | [
"",
"sql",
"ms-access",
"syntax",
"ms-access-2007",
""
] |
I have a login script that verifies a username/password against data in a 'user' table. Furthermore, I have a 'roles' table that specifies the access level of a given user. Assuming I am using safe login scripts, are there any security holes in simply performing an additional query, upon successful login, against the 'roles' table to discover the user's authorization level and storing this into a session variable? The idea would then be that on any page with mixed authority, I could simply query the session variable to discover the logged in user's authorization level.
Thanks. | Sessions are significantly safer than, say, cookies. But it is still possible to steal a session and thus the hacker will have total access to whatever is in that session. Some ways to avoid this are IP Checking (which works pretty well, but is very low fi and thus not reliable on its own), and using a nonce. Typically with a nonce, you have a per-page "token" so that each page checks that the last page's nonce matches what it has stored.
In either security check, there is a loss of usability. If you do IP checking and the user is behind a intranet firewall (or any other situation that causes this) which doesn't hold a steady IP for that user, they will have to re-authenticate every time they lose their IP. With a nonce, you get the always fun "Clicking back will cause this page to break" situation.
But with a cookie, a hacker can steal the session simply by using fairly simple XSS techniques. If you store the user's session ID as a cookie, they are vulnerable to this as well. So even though the session is only penetrable to someone who can do a server-level hack (which requires much more sophisticated methods and usually some amount of privilege, if your server is secure), you are still going to need some extra level of verification upon each script request. You should not use cookies and AJAX together, as this makes it a tad easier to totally go to town if that cookie is stolen, as your ajax requests may not get the security checks on each request. For example, if the page uses a nonce, but the page is never reloaded, the script may only be checking for that match. And if the cookie is holding the authentication method, I can now go to town doing my evilness using the stolen cookie and the AJAX hole. | Only scripts executing on your server have access to the \_SESSION array. If you define the scope of the session cookie, you can even restrict it to a specific directory. The only way someone besides you could get that session data is to inject some PHP code into one of your pages.
As for the system you're using, that is acceptable and is a good way to save database calls, but keep in mind that it will require the user to log out and log in again for any authorization changes to apply. So if you wanted to lock out an account and that user is already logged in, you can't. | How safe are PHP session variables? | [
"",
"php",
"security",
""
] |
I have a requirement where i need to generate html forms on the fly based on many different xml schema's (as of now i have 20 of them and the count keeps increasing). I need to collect data from the user to create instance docs corresponding to each of them and then store the instance docs in db....
challenges
1) schema has lot of unbounded complex types. so we doesnt know in advance the number and type of input types to be created. so pre-creating html etc is not an option
2) even if i can handle generation of the form on the fly, the problem is collecting the data entered..as forms generated dynamically should/will have dynamic id/names for input types
Can anyone suggest the best way to implement this?
thank you in advance | It seems to me like a clear case for XSLT.
Generating HTML from XML through XSLT is the primary goal of XSLT.
As for the id/names, you can create an XSLT which will also generate a set of id/names in a way that you can use. | Use [WSDL2XForms](http://wsdl2xforms.sourceforge.net/) to create XForms from XML Schemas (XSD). Then publish them with Chiba (chiba.sourceforge.net) - it converts these XForms to standard HTML forms on the server side. | web form generation out of xml schema | [
"",
"java",
""
] |
I'm Trying to make a long stored procedure a little more manageable, Is it wrong to have a stored procedures that calls other stored procedures for example I want to have a sproc that inserts data into a table and depending on the type insert additional information into table for that type, something like:
```
BEGIN TRANSACTION
INSERT INTO dbo.ITSUsage (
Customer_ID,
[Type],
Source
) VALUES (
@Customer_ID,
@Type,
@Source
)
SET @ID = SCOPE_IDENTITY()
IF @Type = 1
BEGIN
exec usp_Type1_INS @ID, @UsageInfo
END
IF @TYPE = 2
BEGIN
exec usp_Type2_INS @ID, @UsageInfo
END
IF (@@ERROR <> 0)
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION
```
Or is this something I should be handling in my application? | We call procs from other procs all the time. It's hard/impossible to segment a database-intensive (or database-only) application otherwise. | Calling a procedure from inside another procedure is perfectly acceptable.
However, in Transact-SQL relying on @@ERROR is prone to failure. Case in point, your code. It will fail to detect an insert failure, as well as any error produced inside the called procedures. This is because @@ERROR is reset with each statement executed and only retains the result of the very last statement. I have a blog entry that shows a [correct template of error handling in Transact-SQL](http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/) and transaction nesting. Also Erland Sommarskog has an article that is, for long time now, the [reference read on error handling in Transact-SQL](http://www.sommarskog.se/error-handling-I.html). | Is having a stored procedure that calls other stored procedures bad? | [
"",
"sql",
"sql-server",
""
] |
I have a simple xaml control with the following Grid Row definition:
```
<Grid.RowDefinitions>
<RowDefinition Height="15*" />
<RowDefinition Height="60*" />
<RowDefinition Height="20*" />
<RowDefinition Height="20*" />
<RowDefinition Height="15*" />
</Grid.RowDefinitions>
```
Rows 1-3 each hold a text block which may or may not have text in it. In the code behind I want to minimise the RowDefinition if there is no text. Essentially I have the following in my code behind:
```
if(textblock.Text != ""){
grid.RowDefinitions[elementRow].Height = new GridLength(20, GridUnitType.Star);
}
else{
grid.RowDefinitions[elementRow].Height = new GridLength(0, GridUnitType.Star);
}
```
I want rows 0 and 4 to stay as they are defined in the xaml. Unfortunatly this does not work even though there is text in the text block on row 2 nothing is displayed.
Am I doing something wrong.
Any help is appreciated,
James | Don't use the star notation, use Auto for your RowDefinitions. If the TextBlock.Text is empty, set the Visibility of the TextBlock to Visibility.Collapsed. The grid row will then automatically shrink to nothing. | This is not the answer to your question, just some info.
The \* in the Height (or width for columns) means that the row (or column) width Height="\*" (or Width="\*") will take up the rest of the space. So if you have a grid with 4 rows in a grid with Height="100", if you do this:
```
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="10" />
<RowDefinition Height="10" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
```
The row width Height="\*" will be 70 DIUs (device independent units).
Adding a number before the asterisk (Height="2\*") only works if there are more than one rows using the asterisk, the number before the asterisk indicates how much more space will that specific row take (2\* = twice as much, 3\* three times as much, so on...). I. E.:
```
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="10" />
<RowDefinition Height="2*" /> <!-- this row will be twice as tall as the one below -->
<RowDefinition Height="*" />
</Grid.RowDefinitions>
```
Here the 3rd row will have a height of 54 DIUs (twice as much as the 4th row which has a height of 26 DIUs approx.), both heights sum 80, which is the rest of the space of the grid (10 + 10 + 26 + 54 = 100, the grid height).
BTW, I agree with Charlie's answer. | Dynamic RowDefinition Height | [
"",
"c#",
"wpf",
"grid",
""
] |
is there a way to iterate an object properties and methods. i need to write a utility function like so:
```
function iterate(obj)
{
//print all obj properties
//print all obj methods
}
```
so running this function:
```
iterate(String);
```
will print:
```
property: lenght
function: charAt
function: concat...
```
any ideas? | See my answer in [this other question](https://stackoverflow.com/questions/1200562/difference-in-json-objects-using-javascript-jquery/1200713#1200713), but you can't read built-in properties like that. | Should be as simple as this:
```
function iterate(obj) {
for (p in obj) {
console.log(typeof(obj[p]), p);
}
}
```
Note: The `console.log` function is assuming you are using [firebug](http://getfirebug.com/). At this point, the following:
```
obj = {
p1: 1,
p2: "two",
m1: function() {}
};
iterate(obj);
```
would return:
```
number p1
string p2
function m1
``` | iterating an object properties | [
"",
"javascript",
""
] |
This is probably a C++ 101 question: I'm curious what the guidelines are for using `size_t` and `offset_t`, e.g. what situations they are intended for, what situations they are not intended for, etc. I haven't done a lot of portable programming, so I have typically just used something like `int` or `unsigned int` for array sizes, indexes, and the like. However, I gather it's preferable to use some of these more standard typedefs when possible, so I'd like to know how to do that properly.
As a follow-up question, for development on Windows using Visual Studio 2008, where should I look to find the actual typedefs? I've found `size_t` defined in a number of headers within the VS installation directory, so I'm not sure which of those I should use, and I can't find `offset_t` anywhere. | You are probably referring to `off_t`, not `offset_t`. `off_t` is a POSIX type, not a C type, and it is used to denote file offsets (allowing 64-bit file offsets even on 32-bit systems). C99 has superceded that with `fpos_t`.
`size_t` is meant to count bytes or array elements. It matches the address space. | Instead of `offset_t` do you mean `ptrdiff_t`? This is the type returned by such routines as `std::distance`. My understanding is that `size_t` is unsigned (to match the address space as previously mentioned) whereas `ptrdiff_t` is signed (to theoretically denote "backwards" distances between pointers, though this is very rarely used). | guidelines on usage of size_t and offset_t? | [
"",
"c++",
""
] |
I am new to oracle. I need to process large amount of data in stored proc. I am considering using Temporary tables. I am using connection pooling and the application is multi-threaded.
Is there a way to create temporary tables in a way that different table instances are created for every call to the stored procedure, so that data from multiple stored procedure calls does not mix up? | You say you are new to Oracle. I'm guessing you are used to SQL Server, where it is quite common to use temporary tables. Oracle works differently so it is less common, because it is less necessary.
Bear in mind that using a temporary table imposes the following overheads:
1. read data to populate temporary table- write temporary table data to file- read data from temporary table as your process starts
Most of that activity is useless in terms of helping you get stuff done. A better idea is to see if you can do everything in a single action, preferably pure SQL.
---
Incidentally, your mention of connection pooling raises another issue. A process munging large amounts of data is not a good candidate for running in an OLTP mode. You really should consider initiating a background (i.e. asysnchronous) process, probably a database job, to run your stored procedure. This is especially true if you want to run this job on a regular basis, because we can use DBMS\_SCHEDULER to automate the management of such things. | IF you're using transaction (rather than session) level temporary tables, then this may already do what you want... so long as each call only contains a single transaction? (you don't quite provide enough detail to make it clear whether this is the case or not)
So, to be clear, so long as each call only contains a single transaction, then it won't matter that you're using a connection pool since the data will be cleared out of the temporary table after each COMMIT or ROLLBACK anyway.
(Another option would be to create a uniquely named temporary table in each call using EXECUTE IMMEDIATE. Not sure how performant this would be though.) | Local Temporary table in Oracle 10 (for the scope of Stored Procedure) | [
"",
"sql",
"database",
"oracle",
"stored-procedures",
"temp-tables",
""
] |
Here is a design though: For example is I put a link such as
> <http://example.com>
in **textarea**. How do I get PHP to detect it’s a `http://` link and then print it as
```
print "<a href='http://www.example.com'>http://www.example.com</a>";
```
*I remember doing something like this before however, it was not fool proof it kept breaking for complex links.*
Another good idea would be if you have a link such as
> <http://example.com/test.php?val1=bla&val2blablabla%20bla%20bla.bl>
fix it so it does
```
print "<a href='http://example.com/test.php?val1=bla&val2=bla%20bla%20bla.bla'>";
print "http://example.com/test.php";
print "</a>";
```
This one is just an after thought.. stackoverflow could also probably use this as well :D
Any Ideas | Let's look at the requirements. You have some user-supplied plain text, which you want to display with hyperlinked URLs.
1. The "http://" protocol prefix should be optional.
2. Both domains and IP addresses should be accepted.
3. Any valid top-level domain should be accepted, e.g. .aero and .xn--jxalpdlp.
4. Port numbers should be allowed.
5. URLs must be allowed in normal sentence contexts. For instance, in "Visit stackoverflow.com.", the final period is not part of the URL.
6. You probably want to allow "https://" URLs as well, and perhaps others as well.
7. As always when displaying user supplied text in HTML, you want to prevent [cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) (XSS). Also, you'll want ampersands in URLs to be [correctly escaped](http://www.htmlhelp.com/tools/validator/problems.html#amp) as &.
8. You probably don't need support for IPv6 addresses.
9. **Edit**: As noted in the comments, support for email-adresses is definitely a plus.
10. **Edit**: Only plain text input is to be supported – HTML tags in the input should not be honoured. (The Bitbucket version supports HTML input.)
**Edit**: Check out [GitHub](https://github.com/kwi-dk/UrlLinker) for the latest version, with support for email addresses, authenticated URLs, URLs in quotes and parentheses, HTML input, as well as an updated TLD list.
Here's my take:
```
<?php
$text = <<<EOD
Here are some URLs:
stackoverflow.com/questions/1188129/pregreplace-to-detect-html-php
Here's the answer: http://www.google.com/search?rls=en&q=42&ie=utf-8&oe=utf-8&hl=en. What was the question?
A quick look at http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax is helpful.
There is no place like 127.0.0.1! Except maybe http://news.bbc.co.uk/1/hi/england/surrey/8168892.stm?
Ports: 192.168.0.1:8080, https://example.net:1234/.
Beware of Greeks bringing internationalized top-level domains: xn--hxajbheg2az3al.xn--jxalpdlp.
And remember.Nobody is perfect.
<script>alert('Remember kids: Say no to XSS-attacks! Always HTML escape untrusted input!');</script>
EOD;
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
// Solution 1:
function callback($match)
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">'
. $match[2] . $match[3] . $match[4] . '</a>';
}
print "<pre>";
print preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
'callback', htmlspecialchars($text));
print "</pre>";
```
* To properly escape < and & characters, I throw the whole text through htmlspecialchars before processing. This is not ideal, as the html escaping can cause misdetection of URL boundaries.
* As demonstrated by the "And remember.Nobody is perfect." line (in which remember.Nobody is treated as an URL, because of the missing space), further checking on valid top-level domains might be in order.
**Edit**: The following code fixes the above two problems, but is quite a bit more verbose since I'm more or less re-implementing `preg_replace_callback` using `preg_match`.
```
// Solution 2:
$validTlds = array_fill_keys(explode(" ", ".aero .asia .biz .cat .com .coop .edu .gov .info .int .jobs .mil .mobi .museum .name .net .org .pro .tel .travel .ac .ad .ae .af .ag .ai .al .am .an .ao .aq .ar .as .at .au .aw .ax .az .ba .bb .bd .be .bf .bg .bh .bi .bj .bm .bn .bo .br .bs .bt .bv .bw .by .bz .ca .cc .cd .cf .cg .ch .ci .ck .cl .cm .cn .co .cr .cu .cv .cx .cy .cz .de .dj .dk .dm .do .dz .ec .ee .eg .er .es .et .eu .fi .fj .fk .fm .fo .fr .ga .gb .gd .ge .gf .gg .gh .gi .gl .gm .gn .gp .gq .gr .gs .gt .gu .gw .gy .hk .hm .hn .hr .ht .hu .id .ie .il .im .in .io .iq .ir .is .it .je .jm .jo .jp .ke .kg .kh .ki .km .kn .kp .kr .kw .ky .kz .la .lb .lc .li .lk .lr .ls .lt .lu .lv .ly .ma .mc .md .me .mg .mh .mk .ml .mm .mn .mo .mp .mq .mr .ms .mt .mu .mv .mw .mx .my .mz .na .nc .ne .nf .ng .ni .nl .no .np .nr .nu .nz .om .pa .pe .pf .pg .ph .pk .pl .pm .pn .pr .ps .pt .pw .py .qa .re .ro .rs .ru .rw .sa .sb .sc .sd .se .sg .sh .si .sj .sk .sl .sm .sn .so .sr .st .su .sv .sy .sz .tc .td .tf .tg .th .tj .tk .tl .tm .tn .to .tp .tr .tt .tv .tw .tz .ua .ug .uk .us .uy .uz .va .vc .ve .vg .vi .vn .vu .wf .ws .ye .yt .yu .za .zm .zw .xn--0zwm56d .xn--11b5bs3a9aj6g .xn--80akhbyknj4f .xn--9t4b11yi5a .xn--deba0ad .xn--g6w251d .xn--hgbk6aj7f53bba .xn--hlcj6aya9esc7a .xn--jxalpdlp .xn--kgbechtv .xn--zckzah .arpa"), true);
$position = 0;
while (preg_match("{\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))}", $text, &$match, PREG_OFFSET_CAPTURE, $position))
{
list($url, $urlPosition) = $match[0];
// Print the text leading up to the URL.
print(htmlspecialchars(substr($text, $position, $urlPosition - $position)));
$domain = $match[2][0];
$port = $match[3][0];
$path = $match[4][0];
// Check if the TLD is valid - or that $domain is an IP address.
$tld = strtolower(strrchr($domain, '.'));
if (preg_match('{\.[0-9]{1,3}}', $tld) || isset($validTlds[$tld]))
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1][0] ? $url : "http://$url";
// Print the hyperlink.
printf('<a href="%s">%s</a>', htmlspecialchars($completeUrl), htmlspecialchars("$domain$port$path"));
}
else
{
// Not a valid URL.
print(htmlspecialchars($url));
}
// Continue text parsing from after the URL.
$position = $urlPosition + strlen($url);
}
// Print the remainder of the text.
print(htmlspecialchars(substr($text, $position)));
``` | You guyz are talking way to advance and complex stuff which is good for some situation, but mostly we need a simple careless solution. How about simply this?
```
preg_replace('/(http[s]{0,1}\:\/\/\S{4,})\s{0,}/ims', '<a href="$1" target="_blank">$1</a> ', $text_msg);
```
Just try it and let me know what crazy url it doesnt satisfy. | Replace URLs in text with HTML links | [
"",
"php",
"regex",
"url",
"preg-replace",
"linkify",
""
] |
I am trying to save unicode data (greek) in oracle database (10 g). I have created a simple table:
[](https://i.stack.imgur.com/xApQJ.png)
I understand that NVARCHAR2 always uses UTF-16 encoding so it must be fine for all (human) languages.
Then I am trying to insert a string in database. I have hardcoded the string ("How are you?" in Greek) in code. Then I try to get it back from database and show it.
```
class Program
{
static string connectionString = "<my connection string>";
static void Main (string[] args) {
string textBefore = "Τι κάνεις;";
DeleteAll ();
SaveToDatabase (textBefore);
string textAfter = GetFromDatabase ();
string beforeData = String.Format ("Before: {0}, ({1})", textBefore, ToHex (textBefore));
string afterData = String.Format ("After: {0}, ({1})", textAfter, ToHex (textAfter));
Console.WriteLine (beforeData);
Console.WriteLine (afterData);
MessageBox.Show (beforeData);
MessageBox.Show (afterData);
Console.ReadLine ();
}
static void DeleteAll () {
using (var oraConnection = new OracleConnection (connectionString)) {
oraConnection.Open ();
var command = oraConnection.CreateCommand ();
command.CommandText = "delete from UNICODEDATA";
command.ExecuteNonQuery ();
}
}
static void SaveToDatabase (string stringToSave) {
using (var oraConnection = new OracleConnection (connectionString)) {
oraConnection.Open ();
var command = oraConnection.CreateCommand ();
command.CommandText = "INSERT into UNICODEDATA (ID, UNICODESTRING) Values (11, :UnicodeString)";
command.Parameters.Add (":UnicodeString", stringToSave);
command.ExecuteNonQuery ();
}
}
static string GetFromDatabase () {
using (var oraConnection = new OracleConnection (connectionString)) {
oraConnection.Open ();
var command = oraConnection.CreateCommand ();
command.CommandText = "Select * from UNICODEDATA";
var erpReader = command.ExecuteReader ();
string s = String.Empty;
while (erpReader.Read ()) {
string text = erpReader.GetString (1);
s += text + ", ";
}
return s;
}
}
static string ToHex (string input) {
string bytes = String.Empty;
foreach (var c in input)
bytes += ((int)c).ToString ("X4") + " ";
return bytes;
}
}
```
Here are different outputs:
Text before sending to database in a message box:
[](https://i.stack.imgur.com/SRZGZ.png)
Text after getting from database in a message box:
[](https://i.stack.imgur.com/jTPph.png)
Console Output:
[](https://i.stack.imgur.com/fTFWI.png)
Please can you suggest what I might be doing wrong here? | I can see five potential areas for problems:
1. How are you actually getting the text into your .NET application? If it's hardcoded in a string literal, are you sure that the compiler is assuming the right encoding for your source file?
2. There could be a problem in how you're sending it to the database.
3. There could be a problem with how it's being stored in the database.
4. There could be a problem with how you're fetching it in the database.
5. There could be a problem with how you're displaying it again afterwards.
Now areas 2-4 sound like they're less likely to be an issue than 1 and 5. How are you displaying the text afterwards? Are you actually fetching it out of the database in .NET, or are you using Toad or something similar to try to see it?
If you're writing it out again from .NET, I suggest you skip the database entirely - if you just display the string itself, what do you see?
I have an article you might find useful on [debugging Unicode problems](http://pobox.com/~skeet/csharp/debuggingunicode.html). In particular, concentrate on every place where the encoding *could* be going wrong, and make sure that whenever you "display" a string you dump out the exact Unicode characters (as integers) so you can check those rather than just whatever your current font wants to display.
EDIT: Okay, so the database *is* involved somewhere in the problem.
I *strongly* suggest that you remove anything like ASP and HTML out of the equation. Write a simple console app that does *nothing* but insert the string and fetch it again. Make it dump the individual Unicode characters (as integers) before and after. Then try to see what's in the database (e.g. using Toad). I don't know the Oracle functions to convert strings into sequences of individual Unicode characters and then convert those characters into integers, but that would quite possibly be the next thing I'd try.
EDIT: Two more suggestions (good to see the console app, btw).
1. Specify the data type for the parameter, instead of just giving it an object. For instance:
```
command.Parameters.Add (":UnicodeString",
OracleType.NVarChar).Value = stringToSave;
```
2. Consider using Oracle's own driver instead of the one built into .NET. You may wish to do this anyway, as it's generally reckoned to be faster and more reliable, I believe. | You can determine what characterset your database uses for NCHAR with the query:
```
SQL> SELECT VALUE
2 FROM nls_database_parameters
3 WHERE parameter = 'NLS_NCHAR_CHARACTERSET';
VALUE
------------
AL16UTF16
```
to check if your database configuration is correct, you could run the following in SQL\*Plus:
```
SQL> CREATE TABLE unicodedata (ID NUMBER, unicodestring NVARCHAR2(100));
Table created
SQL> INSERT INTO unicodedata VALUES (11, 'Τι κάνεις;');
1 row inserted
SQL> SELECT * FROM unicodedata;
ID UNICODESTRING
---------- ---------------------------------------------------
11 Τι κάνεις;
``` | How to save unicode data to oracle? | [
"",
"c#",
"oracle",
"unicode",
"oracle10g",
""
] |
I have an asp.net web site which will send several ExecuteNonQuery() statements (stored proc) to the same database (Sql server 2005). MSDTC service is turned off on both web and database servers.
These statements need to run all successfully, all or none. So I need to wrap them in transaction. Is the best way to use SQLTranscation? Attach the Command object to a transaction and then execute these statements through the command object? What kind of error checking needs to be done in the stored procs so that successful commits or rollbacks occur in the code behind? | You could just the [System.Transactions](http://msdn.microsoft.com/en-us/library/ms973865.aspx) class in .NET. You can see some [quickstart examples of how to use them here](http://asp.dotnetheaven.com/howto/doc/transactions/TransactionsWithSQL.aspx). You can then wrap your ExecuteNonQuery() elements in a [TransactionScope](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx):
```
using (TransactionScope ts = new TransactionScope())
{
// Your DB inserts
ts.Complete();
}
``` | See this blog for an example of stored procedure template designed to handle errors and transactions atomically, if possible: [Exception handling and nested transactions](http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/).
In the client you need to either start a SqlTransaction and attach it to each SqlCommand:
```
using (SqlTransaction tn = conn.BeginTransaction())
{
cmd1 = new SqlCommand("...", conn, trn);
cmd1.ExecuteNonQuery();
cmd2 = new SqlCommand("...", conn, trn);
cmd2.ExecuteNonQuery();
...
trn.Commit();
}
```
or you can use the CLR transactions, since ADO.Net is aware of them and will enroll your SqlCommands in the transaction.
No mater what, you'll have to execute all your commands on the same connection, otherwise will require a distributed transaction (even if is on the same server). | Sending several ExecuteNonQuery() to same database, which transaction type and error checking to use? (.NET) | [
"",
"c#",
".net",
"sql-server",
"ado.net",
"transactions",
""
] |
I have a table which has no primary key and I can't add one - the relevant columns from it are:
```
Department | Category |
-------------+-----------+
0001 | A |
0002 | D |
0003 | A |
0003 | A |
0003 | C |
0004 | B |
```
I want to retrieve a single row for each `Department`, which gives me the department code and the `Category` which appears most frequently in the table, i.e.
```
Department | Category |
-------------+-----------+
0001 | A |
0002 | D |
0003 | A |
0004 | B |
```
What is the best way to achieve this? My current attempt involves a `Count(Category)` in a subquery from which the `Max(CountofCategory)` is then taken, but including the `Category` field at this stage means too many rows at returned (since `GROUP BY` is applied at `Category` level as well as `Department`). In the case of a tie, I'd just select the min/max of the category arbitrarily. Ideally this should be database-agnostic, but is likely to run on either Oracle or MySQL. | Works in both Oracle and SQL Server, I believe is all standard SQL, from later standards:
```
with T_with_RN as
(select Department
, Category
, row_number() over (partition by Department order by count(*) Desc) as RN
from T
group by Department, Category)
select Department, Category
from T_with_RN
where RN = 1
```
**EDIT** I don't know why I used the WITH, the solution is probably easier to read using an inline view:
```
select Department, Category
from (select Department
, Category
, row_number() over (partition by Department order by count(*) Desc) as RN
from T
group by Department, Category) T_with_RN
where RN = 1
```
**END EDIT**
Test cases:
```
create table T (
Department varchar(10) null,
Category varchar(10) null
);
-- Original test case
insert into T values ('0001', 'A');
insert into T values ('0002', 'D');
insert into T values ('0003', 'A');
insert into T values ('0003', 'A');
insert into T values ('0003', 'C');
insert into T values ('0004', 'B');
-- Null Test cases:
insert into T values (null, 'A');
insert into T values (null, 'B');
insert into T values (null, 'B');
insert into T values ('0005', null);
insert into T values ('0005', null);
insert into T values ('0005', 'X');
-- Tie Test case
insert into T values ('0006', 'O');
insert into T values ('0006', 'P');
``` | You can try the following as well. Window here returns the Categories ordered by their descending frequency of match against each Department. FIRST\_VALUE() picks the first one from this.
```
SELECT DISTINCT (department),
FIRST_VALUE(category) OVER
(PARTITION BY department ORDER BY count(*) DESC ROWS UNBOUNDED PRECEDING)
FROM T
GROUP BY department, category;
``` | Select most frequently occurring records using two or more grouping columns | [
"",
"sql",
""
] |
What is the recommended way of joining SQL Server database tables located on databases which are on different servers?
All databases will be on the same network. | You can set the servers up as linked servers:
<http://www.sqlservercentral.com/articles/Video/66413/>
You will then be able to run queries that reference the different databases. | Linked servers work - but have some issues that make me try to avoid them:
1. Over time they make managing your environment, from a high level, a nightmare. Servers come and go, get upgraded and so on, and that gets really sketchy when you have hundreds of queries lurking around with servernames hardcoded in (think "... join myRetriringServer.someDatabase.dbo.importantData ..." ). Aliases help, but they are a hassle IMHO. It's an example of problematic tight coupling.
2. Performance can be a very serious problem because cross-server queries of any complexity don't optimize, and you'll find the servers frequently resort on-the-fly copies of whole tables over the wire. (Joe ++)
If you're in a really small environment, it works OK. For bigger environments, I much prefer moving slowly-changing data around with SSIS, and then working to co-locate rapidly changing / dependent data on the same server for performance. | Joining Tables from multiple SQL Server databases located on separate severs | [
"",
"sql",
"sql-server",
"database",
""
] |
I'm curious:
If you do a `printf("%f", number);` what is the precision of the statement? I.e. How many decimal places will show up? Is this compiler dependent? | The ANSI C standard, in section 7.19.6.1, says this about the f format specifier:
> If the precision is missing, 6 digits are given | The book, [C: A Reference Manual](https://rads.stackoverflow.com/amzn/click/com/013089592X) states that if no precision is specified then the default precision is 6 (i.e. 6 digits after the decimal point).
One caveat is if the number is inf (i.e. 1.0/0.0) or NaN then C99 specifies that the output should be inf, -inf, infinity, -infinity, or nan etc.... | What is c printf %f default precision? | [
"",
"c++",
"c",
"printf",
"precision",
""
] |
I am looking for a way to populate a single grid using data bindings.
The way I do this at the moment is by using an ItemsControl where each item is represented as a Grid with the columns that I need. The main reason I want a single grid is to make the widths of all columns line up.
Is there way for the Grid panel to be used with ItemsControl so that there is a single grid to contain all the items?
Or is there another solution? | You can make grid column widths "line up" across grids by using [Grid.IsSharedSizeScope](http://msdn.microsoft.com/en-us/library/system.windows.controls.grid.issharedsizescope.aspx) and [SharedSizeGroup](http://msdn.microsoft.com/en-us/library/system.windows.controls.grid.issharedsizescope.aspx).
You simply need to set the Grid.IsSharedSizeScope property to true on the element that contains your grids, then set the SharedSizeGroup on the ColumnDefinitions you want to have the same width.
Both of the links above have examples. | Why not just use [`DataGrid`](http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29117)? | How to dynamically populate a WPF grid using data binding? | [
"",
"c#",
"wpf",
"wpf-controls",
""
] |
I'm building a System.Drawing.Bitmap in code from a byte array, and i'm not sure what properties and such need to be set so that it will properly save as a .BMP file. I have `Bitmap b = new Bitmap(width, height, PixelFormat.Format32bppArgb);` as my constructor and
```
for (int i = 1; i < data.Length; i += 2;)
{
Color c = new Color();
c.A = data[i];
c.R = data[i];
c.G = data[i];
c.B = data[i];
int x = (i + 1) / 2;
int y = x / width;
x %= width;
b.SetPixel(x, y, c);
}
```
as the code that sets the bitmap data (it's reading from a byte array containing 16 bit little'endian values and converting them to grayscale pixels). What else should be done to make this bitmap saveable? | Nothing else needs to be done, you can save the bitmap right after setting it's image data.
Also note that the `SetPixel` method used in a loop is utterly slow, [see this link for more information.](https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx) | An instance of the `Bitmap` class can be saved as a .bmp file just by calling the `Save(string filename)` method.
As mentioned in other answers, setting the pixels one at a time in a loop is a bit slow.
Also, you can't set the properties of a `Color` struct, you will need to create it as follows:
```
Color c = Color.FromArgb(data[i], data[i + 1], data[i + 2], data[i + 3]);
```
(Not sure what is in your data[] array) | Constructing a bitmap from code; what steps are necessary? | [
"",
"c#",
".net",
"image-processing",
""
] |
I have a table T with a primary key id and foreign key f. Is f automatically indexed when it is specified as a foreign key? Do I need explicitly add an index for f ? | No index is created so yes, you need add explicitly add an index.
**Edited to add...**
I probably ought to add that the source table/column for the data in table T must have a unique index. If you try and make an FK to a column that isn't a unique index (either as a PK or with a UNIQUE constraint), the FK can't be created. | No, it is a constraint, not an index.
see [Are foreign keys indexed automatically in SQL Server?](https://stackoverflow.com/questions/278982/are-foreign-keys-indexed-automatically-in-sql-server) | Does specifying a foreign key make it an index? | [
"",
"sql",
"sql-server",
""
] |
I am creating several XmlElements used in a larger XML Document.
```
XmlElement thisElement = xmlSearchParameters.CreateElement("value");
thisElement.InnerXml = this.searchParameters[key];
```
This works well for most instances, but if the value of searchParameters[key] happens to include an & symbol, I get one of the two following errors:
Unexpected end of file has occurred. Line 1, position 1. - if value is ONLY &
An error occurred while parsing EntityName. Line 1, position 7. - if value contains & mixed with other text.
What is the prefered way of including & and any other special symbols in an XmlElement? I suspect there must be a better way than just replacing & with something else (some sort of XmlFormat method???). | Why do you use `InnerXml` in the first place? It's supposed to be used if you have some *valid* markup in unparsed string form, and want to insert it there. For plain text, use `InnerText`:
```
thisElement.InnerText = this.searchParameters[key];
``` | If you use InnerXml you have to guarantee that text value is valid xml.
Use InnerText property instead of InnerXml. | Add Ampersand to XmlElement | [
"",
"c#",
"xml",
""
] |
I know I shouldn't be outputting things directly in PHP, but using a template instead, but whatever.
I remember perl being able to do this, and as I reached for my perl book, I realized: I already packed it, as I'm moving. It's incredibly difficult to search for "<<<", as well.
So, I know I can go,
```
echo <<<SOMESTUFF
blah
blah
blah
```
but other than that I'm at a loss... How do I end it? Where do I need semicolons? | In PHP, this syntax is called a [heredoc](https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc). The linked documentation contains some helpful examples. | To end it, type:
```
echo <<<SOMESTUFF
...
SOMESTUFF
```
With `SOMESTUFF` being on a line of its own. See the PHP manual on "heredocs" for more info. | How do I use that "<<<HTML" thing in PHP? | [
"",
"php",
""
] |
Building on [this question](https://stackoverflow.com/questions/1171812/multi-key-dictionary-in-c), is there a simple solution for having a multi-key dictionary where *either key individually* can be used to identify the value?
ie.
```
MultikeyDictionary<TKey1, TKey2, TValue> foo;
foo.Add(key1, key2, value);
myValue = foo[key1];
// value == myValue
foo.Remove(key2);
myValue = foo[key1]; // invalid, Exception or null returned
``` | [This blog post](http://www.fyslexicduck.com/2009/02/multi-key-generic-dictionary-class-for.html) seems to detail a rather decent implementation.
> ### Multi-key generic dictionary class for C#
>
> MultiKeyDictionary is a C# class
> that wraps and extends the Generic
> Dictionary object provided by
> Microsoft in .NET 2.0 and above. This
> allows a developer to create a generic
> dictionary of values and reference the
> value list through two keys instead of
> just the one provided by the Microsoft
> implementation of the Generic
> Dictionary<...>. You can see my
> article on CodeProject (here), however
> this code is more up-to-date and bug
> free. | Yes, define a class that adds the object to an internal hashtable with both keys,
```
public MyClass<k1, k2, T>: Dictionary<object, T>
{
private Dictionary<k1, k2> keyMap;
public new Add(k1 key1Val, k2 key2Val, T object)
{
keyMap.Add(key1Val, key2Val);
base.Add(k2, object)
}
public Remove(k1 key1Val)
{
base.Remove(keyMap[key1Val]);
keyMap.Remove(key1Val);
}
public Remove(k2 key2Val)
{
base.Remove(key2Val);
keyMap.Remove(key2Val);
}
}
``` | Multi-key dictionaries (of another kind) in C#? | [
"",
"c#",
"data-structures",
""
] |
I would like to know how this can be achieved.
Assume: That there's a lot of html code containing tables, divs, images, etc.
Problem: How can I get matches of all occurances. More over, to be specific, how can I get the img tag source (src = ?).
example:
```
<img src="http://example.com/g.jpg" alt="" />
```
How can I print out <http://example.com/g.jpg> in this case. I want to assume that there are also other tags in the html code as i mentioned, and possibly more than one image. Would it be possible to have an array of all images sources in html code?
I know this can be achieved way or another with regular expressions, but I can't get the hang of it.
Any help is greatly appreciated. | While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.
What I recommend you do is use a DOM parser such as [**`SimpleHTML`**](http://simplehtmldom.sourceforge.net/) and use it as such:
```
function get_first_image($html) {
require_once('SimpleHTML.class.php')
$post_html = str_get_html($html);
$first_img = $post_html->find('img', 0);
if($first_img !== null) {
return $first_img->src;
}
return null;
}
```
Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can also get the alt attribute.
A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the `alt` attribute to be after the `src` or the opposite, and to overcome this limitation would add more complexity to the regular expression.
Also, consider the following. To properly match an `<img>` tag using regular expressions and to get only the `src` attribute (captured in group 2), you need the following regular expression:
```
<\s*?img\s+[^>]*?\s*src\s*=\s*(["'])((\\?+.)*?)\1[^>]*?>
```
And then again, the above can fail if:
* The attribute or tag name is in capital and the **`i`** modifier is not used.
* Quotes are not used around the `src` attribute.
* Another attribute then `src` uses the `>` character somewhere in their value.
* Some other reason I have not foreseen.
So again, simply don't use regular expressions to parse a dom document.
---
**EDIT:** If you want all the images:
```
function get_images($html){
require_once('SimpleHTML.class.php')
$post_dom = str_get_dom($html);
$img_tags = $post_dom->find('img');
$images = array();
foreach($img_tags as $image) {
$images[] = $image->src;
}
return $images;
}
``` | Use this, is more effective:
```
preg_match_all('/<img [^>]*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
echo $value."<br>";
}
```
Example:
```
$html = '
<ul>
<li><a target="_new" href="http://www.manfromuranus.com">Man from Uranus</a></li>
<li><a target="_new" href="http://www.thevichygovernment.com/">The Vichy Government</a></li>
<li><a target="_new" href="http://www.cambridgepoetry.org/">Cambridge Poetry</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value1.jpg" />
<li><a href="http://www.verot.net/pretty/">Electronaut Records</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value2.jpg" />
<li><a target="_new" href="http://www.catseye-crew.com">Catseye Productions</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value3.jpg" />
</ul>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="res/upload.jpg" />
<li><a target="_new" href="http://www.manfromuranus.com">Man from Uranus</a></li>
<li><a target="_new" href="http://www.thevichygovernment.com/">The Vichy Government</a></li>
<li><a target="_new" href="http://www.cambridgepoetry.org/">Cambridge Poetry</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value4.jpg" />
<li><a href="http://www.verot.net/pretty/">Electronaut Records</a></li>
<img src="value5.jpg" />
<li><a target="_new" href="http://www.catseye-crew.com">Catseye Productions</a></li>
<img width="190" height="197" border="0" align="right" alt="upload.jpg" title="upload.jpg" class="noborder" src="value6.jpg" />
';
preg_match_all('/<img .*src=["|\']([^"|\']+)/i', $html, $matches);
foreach ($matches[1] as $key=>$value) {
echo $value."<br>";
}
```
Output:
```
value1.jpg
value2.jpg
value3.jpg
res/upload.jpg
value4.jpg
value5.jpg
value6.jpg
``` | Using regular expressions to extract the first image source from html codes? | [
"",
"php",
"html",
"regex",
""
] |
Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (<http://www.newrelic.com/>)?
Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance. | None that I'm aware. django-debug-toolbar is a fairly popular app which can provide you with performance info for a particular page, but feature-wise it doesn't even come close to what the New Relic demo shows (I have no experience with NR/RoR myself). | YES! We (New Relic) just announced our Python agent at DjangoCon this week. Sign up at newrelic.com and enjoy! | Django equivalent of New Relic RPM for Rails? | [
"",
"python",
"django",
""
] |
> **Possible Duplicate:**
> [Why catch and rethrow Exception in C#?](https://stackoverflow.com/questions/881473/why-catch-and-rethrow-exception-in-c)
I sometimes come across C# code that looks like this:
```
try
{
// Some stuff
}
catch (Exception e)
{
throw e;
}
```
I understand its possible to do something like log the exception message and then rethrow it. I'm talking about a catch that only rethrows the exception. I don't see a point to this. I have three questions:
1) Is there any advantage to this
2) Does this slow doen the code at all
3) Would it make any difference if the catch block were as follows:
```
catch (Exception)
{
throw;
}
``` | This rethrows the *exact* same exception:
```
catch (Exception)
{
throw;
}
```
Whereas this rethrows the exception without the original stack trace:
```
catch (Exception e)
{
throw e;
}
```
There is often a good reason for `throw;` as you can log the exception or do other things prior to rethrowing the exception. I am not aware of any good reasons for `throw e;` as you will wipe out the valuable stack trace information. | Not if you do nothing else in the catch... But this is often used to do other things in the catch, such as logging, or other kinds of exception procesing, before rethrowing it. | In .NET, is there any advantage to a try/catch where the catch just rethrows | [
"",
"c#",
".net",
"try-catch",
""
] |
I currently am working on a legacy application and have inherited some shady SQL with it. The project has never been put into production, but now is on it's way. During intial testing I found a bug. The application calls a stored procedure that calls many other stored procedures, creates cursors, loops through cursors, and many other things. FML.
Currently the way the app is designed, it calls the stored procedure, then reloads the UI with a fresh set of data. Of course, the data we want to display is still being processed on the SQL server side, so the UI results are not complete when displayed. To fix this, I just made a thread sleep for 30 seconds, before loading the UI. This is a terrible hack and I would like to fix this properly on the SQL side of things.
My question is...is it worthwhile to convert the branching stored procedures to functions? Would this make the main-line stored procedure wait for a return value, before processing on?
Here is the stored procedure:
```
ALTER PROCEDURE [dbo].[ALLOCATE_BUDGET]
@budget_scenario_id uniqueidentifier
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @constraint_type varchar(25)
-- get project cache id and constraint type
SELECT @constraint_type = CONSTRAINT_TYPE
FROM BUDGET_SCENARIO WHERE BUDGET_SCENARIO_ID = @budget_scenario_id
-- constraint type is Region by Region
IF (@constraint_type = 'Region by Region')
EXEC BUDGET_ALLOCATE_SCENARIO_REGIONBYREGION @budget_scenario_id
-- constraint type is City Wide
IF (@constraint_type = 'City Wide')
EXEC BUDGET_ALLOCATE_SCENARIO_CITYWIDE @budget_scenario_id
-- constraint type is Do Nothing
IF (@constraint_type = 'Do Nothing')
EXEC BUDGET_ALLOCATE_SCENARIO_DONOTHING @budget_scenario_id
-- constraint type is Unconstrained
IF (@constraint_type = 'Unconstrained')
EXEC BUDGET_ALLOCATE_SCENARIO_UNCONSTRAINED @budget_scenario_id
--set budget scenario status to "Allocated", so reporting tabs in the application are populated
EXEC BUDGET_UPDATE_SCENARIO_STATUS @budget_scenario_id, 'Allocated'
END
```
To avoid displaying an incomplete resultset in the calling .NET application UI, before the cursors in the branching calls are completed, is it worthwile to convert these stored procedures into functions, with return values? Would this force SQL to wait before completing the main call to the [ALLOCATED\_BUDGET] stored procedure?
* The last SQL statement call in the stored procedure sets a status to "Allocated". This is happening before the cursors in the previous calls are finished processing. Does making these calls into function calls affect how the stored procedure returns focus to the application?
Any feedback is greatly appreciated. I have a feeling I am correct in going towards SQL functions but not 100% sure.
\*\* additional information:
1. Executing code uses [async=true] in the connection string
2. Executing code uses the [SqlCommand].[ExecuteNonQuery] method | How are you calling the procedure? I'm going to guess that you are using ExecuteNonQuery() to call the procedure. Try calling the procedure using ExecuteScalar() and modify the procedure like the following:
```
ALTER PROCEDURE [dbo].[ALLOCATE_BUDGET]
@budget_scenario_id uniqueidentifier
AS
BEGIN
...
RETURN True
END
```
This should cause your data execution code in .NET to wait for the procedure to complete before continuing. If you don't want your UI to "hang" during the procedure execution, use a BackgroundWorkerProcess or something similar to run the query on a separate thread and look for the completed callback to update the UI with the results. | You could also try using the [RETURN statement](http://msdn.microsoft.com/en-us/library/ms174998.aspx) in your child stored procedures, which can be used to return a result code back to the parent procedure. You can call the child procedure by something along the lines of "`exec @myresultcode = BUDGET_ALLOCATE_SCENARIO_REGIONBYREGION()`". I think this should force the parent procedure to wait for the child procedure to finish. | SQL user-defined functions vs. stored procedure branching | [
"",
"sql",
"stored-procedures",
"function",
"logic",
"cursors",
""
] |
I am having an issue with many-to-many mapping using NHibernate. Basically I have 2 classes in my object model (Scenario and Skill) mapping to three tables in my database (Scenario, Skill and ScenarioSkill). The ScenarioSkills table just holds the IDs of the SKill and Scenario table (SkillID, ScenarioID).
In the object model a Scenario has a couple of general properties and a list of associated skills (IList) that is obtained from the ScenarioSkills table. There is no associated IList of Scenarios for the Skill object.
The mapping from Scenario and Skill to ScenarioSkill is a many-to-many relationship:
Scenario \* --- \* ScenarioSkill \* --- \* Skill
I have mapped out the lists as bags as I believe this is the best option to use from what I have read. The mappings are as follows:
Within the Scenario class
```
<bag name="Skills" table="ScenarioSkills">
<key column="ScenarioID" foreign-key="FK_ScenarioSkill_ScenarioID"/>
<many-to-many class="Domain.Skill, Domain" column="SkillID" />
</bag>
```
And within the Skill class
```
<bag name="Scenarios" table="ScenarioSkills" inverse="true" access="noop" cascade="all">
<key column="SkillID" foreign-key="FK_ScenarioSkill_SkillID" />
<many-to-many class="Domain.Scenario, Domain" column="ScenarioID" />
</bag>
```
Everything works fine, except when I try to delete a skill, it cannot do so as there is a reference constraint on the SkillID column of the ScenarioSkill table. Can anyone help me?
I am using NHibernate 2 on an C# asp.net 3.5 web application solution. | Bit late on the final reply here but this the the mapping I ended up successfully implementing.
In Scenario
```
<bag name="skills" access="field" schema="OSM" table="ScenarioSkill" cascade="none">
<key column="ScenarioID"
foreign-key="FK_ScenarioSkill_Scenario" />
<!-- Skills can be soft-deleted (groan), so ignore them if they don't 'exist' anymore. -->
<many-to-many column="SkillID"
class="DomainModel.Skill, DomainModel"
foreign-key="FK_ScenarioSkill_Skill"
where="IsDeleted = 0"/>
</bag>
```
In Skill
```
<!-- inverse end of scenarios -->
<bag name="scenarios" access="field" inverse="true" schema="OSM" table="ScenarioSkill" cascade="none">
<key column="SkillID"
foreign-key="FK_ScenarioSkill_Skill" />
<many-to-many column="ScenarioID"
class="Scenario"
foreign-key="FK_ScenarioSkill_Scenario" />
</bag>
``` | Unless I'm reading the question incorrectly you need to delete the related ScenarioSkills before you delete a Skill or a Scenario. It's pretty straighforward, you just need a custom method to delete the relates ScenarioSkill objects before you delete the parent record.
Do you want it to delete automatically though? | NHibernate many-to-many mapping | [
"",
"c#",
"nhibernate",
"many-to-many",
""
] |
Just an idea:
example (in PHP):
to set name:
$object->name('name');
to get name:
$object->name();
If no argument: the method is used as getter, else as setter. For simple getters/setter. Stupid, whatever, maybe?
edit: to follow up on the answers: I don't really like **get and set** because I prefer to have the interface as explicit as possible. When there are only a few properties it's also overkill IMHO. So I'd like to narrow it down to classes/objects with a couple of explicit getters/setters. | Sure, you could do that if it makes sense in your application, otherwise I would just use the standard getters/setters which have already been set up for you. Your function could look something like this:
```
public function name($val = null)
{
if (is_null($val))
{
return $this->name;
}
else
{
$this->name = $val;
}
}
``` | The problem is it would be hard to follow. I'd much rather use PHP5's \_\_get and \_\_set so it is more natural to get and set variables, and everyone would know exactly what I am doing. IE:
```
class myClass
{
function __get($name)
{
return $this->array[$name];
}
function __set($name, $value)
{
$this->array[$name] = $value;
}
function print()
{
echo $this->array['test'];
}
}
$obj = new myClass;
$obj->test = "Hi";
echo $obj->test; //echos Hi.
$obj->print(); //echos Hi.
``` | setters/getters in one method | [
"",
"php",
"oop",
"setter",
"getter",
""
] |
I have a method of an object which is something like a factory. You give it a type, it creates an instance and does a few other things. An elegant way to do it (in my opinion) is like this:
```
public T MagicMethod<T>() where T: SomeBaseClass
{
// Magic goes here
}
```
But this upsets FxCop who says that this is a bad style - I get a "CA1004: Generic methods should provide type parameter" warning. Something about not being to use inference and stuff. So, the only other way I can think of is something like this:
```
public SomeBaseClass MagicMethod(Type T)
{
// Same magic goes here
}
```
I believe this is inferior to the first method on many accounts, but the style rule... The MSDN article on the warning even says that there is no reason for suppressing it.
Am I doing it right by suppressing this warning after all? | FXCop warnings are just that - warnings. Just like implicit cast warnings, they serve to let you know that something you're doing may have behavior you're not anticipating, or may not be what you intended.
An implicit cast warning is dealt with by looking at the code, determinining if you really did intend to do that, and if so, adding an explicit cast.
Same thing with FXCop. Look at the warning, look at your code, and determine if the warning is valid. If it is, fix it. If not, suppress it. A suppression is the equivalent of an explicit cast - "Yes, FXCop, I'm sure I want to do this."
If it was really truly an error, it would probably be a compiler error. | I believe you're misunderstanding what FxCop is telling you, probably because its wording is less than ideal. What it means is that *a generic method should provide a parameter that **is of that type***, not that a generic method should have a non-generic overload that provides a runtime `Type` instance. For example,
```
public void DoSomething<T>(T myParam);
```
The `myParam` is the sort of parameter it's referring to. The reason it wants this is, as you suggest, for inference. This allows you to do something like...
```
string foo = "bar";
DoSomething(foo);
```
instead of having to write
```
DoSomething<string>(foo);
```
In your case, it's fine to suppress the warning since you *want* the user to explicitly specify the type. I would suggest, however (assuming that your constructors are parameterless) that you change your `where` to `where T : SomeBaseClass, new()`. This means that it will direct the compiler to require that whatever type is passed in have a parameterless constructor. This also means that you can do `new T()` in your code. | How to pass a type to a method - Type argument vs generics | [
"",
"c#",
"generics",
"parameters",
"types",
"factory",
""
] |
How would I get a list of numbers from the user and then tokenize them.
This is what I have but it doesn't get anything except for the first number:
```
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line = "";
cin >> line;
stringstream lineStream(line);
int i;
vector<int> values;
while (lineStream >> i)
values.push_back(i);
for(int i=0; i<values.size(); i++)
cout << values[i] << endl;
system("PAUSE");
return 0;
}
```
Related Posts:
[C++, Going from string to stringstream to vector](https://stackoverflow.com/questions/455483/c-going-from-string-to-stringstream-to-vectorint)
[Int Tokenizer](https://stackoverflow.com/questions/1141741/int-tokenizer) | I believe cin >> breaks on whitespace, which means you're only getting the first number entered.
try:
```
getline(cin, line);
``` | Here is probably the easiest way to read values from `cin` into a container:
```
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> values;
std::copy(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(values));
// For symmetry with the question copy back to std::cout
std::copy(
values.begin(),
values.end(),
std::ostream_iterator<int>(std::cout,"\n"));
}
``` | get list of numbers from stdin and tokenize them | [
"",
"c++",
"tokenize",
"stringstream",
""
] |
I am attempting to solve performance issues with a large and complex tomcat java web application. The biggest issue at the moment is that, from time to time, the memory usage spikes and the application becomes unresponsive. I've fixed everything I can fix with log profilers and Bayesian analysis of the log files. I'm considering running a profiler on the production tomcat server.
**A Note to the Reader with Gentle Sensitivities:**
I understand that some may find the very notion of profiling a production app offensive. Please be assured that I have exhausted most of the other options. The reason I am considering this is that I do not have the resources to completely duplicate our production setup on my test server, and I have been unable to cause the failures of interest on my test server.
**Questions:**
I am looking for answers which work either for a java web application running on tomcat, or answer this question in a language agnostic way.
* What are the performance costs of profiling?
* Any other reasons why it is a bad idea to remotely connect and profile a web application in production (strange failure modes, security issues, etc)?
* How much does profiling effect the memory foot print?
* Specifically are there java profiling tools that have very low performance costs?
* Any java profiling tools designed for profiling web applications?
* Does anyone have benchmarks on the performance costs of profiling with visualVM?
* What size applications and datasets can visualVM scale to? | [OProfile](http://oprofile.sourceforge.net) and its ancestor [DPCI](http://www-plan.cs.colorado.edu/diwan/7135/p357-anderson.pdf) were developed for profiling production systems. The overhead for these is very low, and they profile your *full system*, including the kernel, so you can find performance problems in the VM *and* in the kernel and libraries.
To answer your questions:
1. **Overhead:** These are *sampled* profilers, that is, they generate timer or [performance counter](http://en.wikipedia.org/wiki/Hardware_performance_counter) interrupts at some regular interval, and they take a look at what code is currently executing. They use that to build a histogram of where you spend your time, and the overhead is very low (1-8% is what [they claim](http://oprofile.sourceforge.net/about/)) for reasonable sampling intervals.
Take a look at [this graph](http://oprofile.sourceforge.net/performance/) of sampling frequency vs. overhead for OProfile. You can tune the sampling frequency for lower overhead if the defaults are not to your liking.
2. **Usage in production:** The only caveat to using OProfile is that you'll need to install it on your production machine. I believe there's kernel support in Red Hat since RHEL3, and I'm pretty sure other distributions support it.
3. **Memory:** I'm not sure what the exact memory footprint of OProfile is, but I believe it keeps relatively small buffers around and dumps them to log files occasionally.
4. **Java:** OProfile includes profiling agents that support Java and that are aware of code running in JITs. So you'll be able to see Java calls, not just the C calls in the interpreter and JIT.
5. **Web Apps:** OProfile is a system-level profiler, so it's not aware of things like sessions, transactions, etc. that a web app would have.
That said, it is a *full-system* profiler, so if your performance problem is caused by bad interactions between the OS and the JIT, or if it's in some third-party library, you'll be able to see that, because OProfile profiles the kernel and libraries. This is an advantage for production systems, as you can catch problems that are due to misconfigurations or particulars of the production environment that might not exist in your test environment.
6. **VisualVM:** Not sure about this one, as I have no experience with VisualVM
Here's [a tutorial](http://www.ibm.com/developerworks/linux/library/l-oprof.html) on using OProfile to find performance bottlenecks. | I've used YourKit to profile apps in a high-load production environment, and while there was certainly an impact, it was easily an acceptable one. Yourkit [makes a big deal](http://www.yourkit.com/docs/80/help/overhead.jsp) of being able to do this in a non-invasive manner, such as selectively turning off certain profiling features that are more expensive (it's a sliding scale, really).
My favourite aspect of it is that you can run the VM with the YourKit agent running, and it has zero performance impact. it's only when you connect the GUI and start profiling that it has an effect. | Performance Cost of Profiling a Web-Application in Production | [
"",
"java",
"language-agnostic",
"profiling",
"production-environment",
"visualvm",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.