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 WCF service with a private constructor. If I'm not wrong, constructors must be parameterless in WCF and the parameter I need is the caller's name (or caller's method name), so I can assign a few readonly fields.
Is there a way that I can get the caller's name -- or the method that invoked it? I was playing around with OperationContext.Current, but without any luck. | I wouldn't recommend accessing the stack trace for performance reasons.
WCF service constructors only need to be parameterless if you are using the default [ServiceHostFactory](http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory(loband).aspx). You can specify a custom service factory in your .svc file like this:
```
<%@ ServiceHost Language="C#" Debug="true"
Service="Namespace.To.Service"
Factory="Namespace.To.ServiceFactory" %>
```
The process to creating your class in a custom way goes like this:
1. Your [ServiceHostFactory](http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory(loband).aspx) creates an instance of your custom [ServiceHost](http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx) in CreateServiceHost
2. ServiceHost overrides [OnOpening](http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.communicationobject.onopening(loband).aspx) and adds a custom [IServiceBehavior](http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior(loband).aspx) to Description.[Behaviors](http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedescription.behaviors(loband).aspx) (Description is a property on the base class)
3. Your IServiceBehavior implements [ApplyDispatchBehavior](http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.applydispatchbehavior(loband).aspx) and enumerates serviceHostBase.[ChannelDispatchers](http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehostbase.channeldispatchers(loband).aspx), checking if each is a [ChannelDispatcher](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.channeldispatcher(loband).aspx).
* Each ChannelDispatcher's [Endpoints](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.channeldispatcher.endpoints(loband).aspx) property is enumerated and it's DispatchRuntime.[InstanceProvider](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.dispatchruntime.instanceprovider(loband).aspx) is changed to a custom [IInstanceProvider](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider(loband).aspx)
4. The custom IInstanceProvider creates the instance in [GetInstance](http://msdn.microsoft.com/en-us/library/ms587089(loband).aspx)
I have used this to delegate creation to an IoC container. | You can access the .NET call stack like this:
```
var trace = new System.Diagnostics.StackTrace();
var frame = trace.GetFrame( 1 ); // Frame 0 is current function
var callingMethodName = frame.GetMethod().Name;
```
I do not know whether this technique works in your situation, but you could give it a try. | Get the name of caller (or method) that created the WCF Service instance? | [
"",
"c#",
"wcf",
""
] |
I'd like to write a doctest like this:
```
"""
>>> print a.string()
foo : a
bar : b
date : <I don't care about the date output>
baz : c
"""
```
Is there any way to do this? I think it would make more sense to switch to unittest, but I'm curious whether it's possible to specify a range of output that shouldn't be matched for the test in doctest.
Thanks! | With `doctest.ELLIPSIS`, you can use `...` to mean "match any string here". You can set `doctest` options with a doctest directive, to make it active for just one test case: one example in the [online docs](http://docs.python.org/library/doctest.html) is:
```
>>> print range(20) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19]
```
If you want a doctest option to be active throughout, you can pass it as the `optionflags=` argument to whatever doctest functions you use, e.g. `doctest.testfile`. (You can pass multiple option flags there by using the `|` operator to bit-or them). | Responding to questions about "how can we ignore the whole line": yes, the fact that "..." also looks like a continuation like makes it hard to ignore the entire output. You can use "#doctest: +SKIP" if you just want to skip the example entirely, but that won't work if you are relying on its side-effects. If you *really* need to do this, I suppose you could monkey-patch the doctest module itself, though I wouldn't particularly recommend it:
```
>>> import doctest
>>> doctest.ELLIPSIS_MARKER = '-etc-'
>>> print 12 # doctest: +ELLIPSIS
-etc-
```
(this test passes.)
Or you could temporarily suppress stdout and/or stderr:
```
>>> # Suppress stdout
>>> import sys
>>> class DevNull:
... def noop(*args, **kwargs): pass
... close = write = flush = writelines = noop
>>> sys.stdout = DevNull()
>>> # Run a test and ignore output (but we need its side effects)
>>> print 12 # NOTE: stdout is suppressed!
>>> # Restore stdout
>>> sys.stdout = sys.__stdout__
```
(this test also passes.) | Can python doctest ignore some output lines? | [
"",
"python",
"doctest",
""
] |
How can i shorter below codes than before?
i need short and simple method:
i dont want to use foreach loop because i have one value.
```
public partial class Test : System.Web.UI.Page
{
StaffManagementEntities staffContext;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadStaffPersonel();
}
}
void LoadStaffPersonel()
{
int selectedDepartman = Convert.ToInt32(Request.QueryString["SelectedDepartmanID"]);
string name="";
using (staffContext = new StaffManagementEntities())
{
var DepartmanName = from d in staffContext.Departman
where d.ID == selectedDepartman
select d;
foreach (Departman d in DepartmanName)
{
name = d.Name;
}
ObjectResult<StaffsPersonel> personalData = staffContext.GetPersonelData(name);
gvPersonel.DataSource = personalData;
gvPersonel.DataBind();
}
}
}
```
How to use string value instead of " var DepartmanName " | Something like:
```
string name = (from d in staffContext.Departman
where d.ID == selectedDepartman
select d.Name).First();
```
or:
```
string name = staffContext.Departman.Where(d=>d.ID == selectedDepartman)
.First().Name;
``` | Is this what you are trying to do?
```
string name = (from d in staffContext.Departman
where d.ID == selectedDepartman
select d.Name).SingleOrDefault();
```
The **SingleOrDefault** will return the name or null if the department does not exit.
**Update:**
* Seems like you at the moment need to use the **First** method as **ykaratoprak** commented. But according to [this post](http://blogs.msdn.com/adonet/archive/2009/05/18/sneak-preview-entity-framework-4-0-testability-improvements.aspx) the Single/SingleOrDefault will be added in Entity Framework 4.0. | Modify linq query how to? | [
"",
"c#",
".net",
"asp.net",
"linq",
"linq-to-entities",
""
] |
Is is possible (without external library such as boost) to prompt for input from the user, like using cin, but with a default choice that is editable by the user (without a GUI)?
For example, the program will say:
```
Give your input: default
```
and the user can press enter to use "default" or press 1 then enter to get "default1", etc.
EDIT for clarification:
What I current have in my program is providing the default in the prompt (as in one of the answer below). But I'm writing for very special cases where having a editable default is extremely time saving (and 90% of the time, all the user needs is adding a suffix to the default). I can prompt for the suffix only, but then I lost flexibility to edit the default in the other 10% of the cases. | You may want to use [GNU readline](http://tiswww.case.edu/php/chet/readline/rltop.html). | This is usually done slightly differently than you've described. It's fairly common (at least as I've seen) to present the default option as *part of the prompt* rather than after it. For example:
```
Please enter a year (default: 2009):
```
or
```
Do you really want to exit (N):
```
This has the added advantage that if the user *does* want to enter his/her own value rather than the default, he/she doesn't need to delete an existing value in order to do so, which is poor usability and rather frustrating, especially if dealing with a long series of questions/prompts.
It also requires no special libraries and significantly less extra code. | Prompt with editable default in c++? | [
"",
"c++",
"user-interface",
""
] |
What the title says. Is there a way to change intellisense settings (intellisense box size and things like that)? | You can resize the intellisense box size simply by dragging the lower right corner with the mouse. Just like any other window. | I think all the settings for the intellisense and TextEditor are in
Tools->Options->Text Editor | How do i change the intellisense settings in VS2008? | [
"",
"c#",
"visual-studio-2008",
"intellisense",
""
] |
How do I add a class for the `div`?
```
var new_row = document.createElement('div');
``` | *This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.*
---
```
new_row.className = "aClassName";
```
Here's more information on MDN: [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) | Use the `.classList.add()` method:
```
const element = document.querySelector('div.foo');
element.classList.add('bar');
console.log(element.className);
```
```
<div class="foo"></div>
```
This method is better than overwriting the `className` property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using `element.classList` (see [the MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)). | How can I add a class to a DOM element in JavaScript? | [
"",
"javascript",
"dom",
""
] |
What is the cost of [`len()`](https://docs.python.org/2/library/functions.html#len) function for Python built-ins? (list/tuple/string/dictionary) | It's **O(1)** (constant time, not depending of actual length of the element - very fast) on every type you've mentioned, plus `set` and others such as `array.array`. | Calling `len()` on those data types is **O(1)** in [CPython](http://www.python.org), the official and most common implementation of the Python language. Here's a link to a table that provides the algorithmic complexity of many different functions in CPython:
[TimeComplexity Python Wiki Page](http://wiki.python.org/moin/TimeComplexity) | Cost of len() function | [
"",
"python",
"collections",
"time-complexity",
""
] |
Is there any performance differences between string.Format and String.Format ?
As far as i understand string is a shortcut for System.String and there's no difference between them. Am i right?
Thanks! | Those are exactly the same. "string" is just an alias for "System.String" in C# | string and String both resolve to System.String. So no there is no difference at all. | String.Format against string.Format. Any issues? | [
"",
"c#",
"string",
""
] |
I'm porting a few java gwt projects into eclipse and the projects depends on many external .jar files, some of the dependencies seem to be dynamically linked so eclipse isn't picking up the missing links while running the ide.
At run time, I often get exceptions that say for example 'import bar.foo.XML' is missing or some FooBar class definition is missing and it always takes me a while to figure out which .jar file these classes/libraries belong to so I can add them to the run path.
Is there a quick way to search which .jar files contain what classes and what other library they depend on? | An oldie, but still good, and integrated into eclipse:
~~[JarClassFinder](http://www.alphaworks.ibm.com/tech/jarclassfinder/download):~~

Update 2013: the project still exists in a different form as an independent app [JarClassFinder](http://sourceforge.net/projects/jarclassfinder/).
In term of Eclipse plugin, it is no longer maintained, and you only have variant like "[BundleclassFinder](http://sourceforge.net/apps/mediawiki/bclassfinder/index.php?title=Main_Page)".
Other (manual) ways to find a class within jars: "[Java: How do I know which jar file to use given a class name?](https://stackoverflow.com/questions/275120/java-how-do-i-know-which-jar-file-to-use-given-a-class-name)" | You need a tool like [Jar Analyzer](http://www.kirkk.com/main/Main/JarAnalyzer) | searching through .jar files eclipse | [
"",
"java",
"eclipse",
"jar",
""
] |
Which C++ cross-platform GUI toolkit gives smallest footprint with both static and dynamic builds? I don't need a very sophisticated GUI, just basic controls & widgets. | the smallest one I've heard of is [fltk](http://fltk.org) | The Tk from [Tcl/Tk](http://www.tcl.tk/) is well known of its small memory footprint. Details in [Memory Footprint Comparisons](http://wiki.tcl.tk/1131) on Tcl/Tk Wiki. Both, Tcl and Tk, are extremely simple to use with [C++/Tcl](http://cpptcl.sourceforge.net/) and [C++/Tk](http://cpptk.sourceforge.net/) libraries. They were inspired by [Boost.Python](http://www.boost.org/doc/libs/release/libs/python/doc/) | Tiny C++ cross-platform GUI toolkit | [
"",
"c++",
"user-interface",
"cross-platform",
""
] |
I have a class that occasionally gets passed `null` for `File` objects. During normal operation it uses a `Scanner` class to parse through the file.
Instead of littering my code with `null` checks against the `File` objects, I thought I could replace the `File`s with nullobjects (Gang of Four style).
However, it looks like `File` isn't really designed to be extended. Does any one have any pointers on how to do this? | You can replace the object that uses the file with a NullObject
For instance, you can use a NullInputStream and pass it to the scanner.
Before:
```
public void whatever( File f ) {
Scanner scanner = new Scanner( f );
...
}
```
After
```
public void whatever( File f ) {
Scanner scanner = new Scanner( getInputStreamFrom( f ) );
...
}
```
And have that method implemented like:
```
private final InputStream getInputStreamFrom( File f ) {
if( f == null && !f.exists() ) {
return NullInputStream.instance;
}
return new InputStream( new FileInputStream( f ) );
}
class NulllInputStream extends InputStream {
private final static NullInputStream instance = new NullInputStream();
private NullInputStream() {
}
public int read() {
return -1;
}
.... other relevant methods here...
}
```
Obviously coded carefully and not in 3 mins. as I did :) :) :) | Why can't you just control the entry point of the `File` object into your program's logic and perform the `null` check there?
Another option would be to use something like a separate interface which encapsulates the data: a `Reader` for example. You could certainly provide a `NullReader` implementation | nullobject for File in Java | [
"",
"java",
"design-patterns",
"file",
"null",
"mocking",
""
] |
I have an array in Javascript:
```
var array = new array();
array[0] = "apples";
array[1] = "oranges";
array[2] = "pears";
```
In PHP, with a given array, I can use the following to loop through an array, and break up the keys and values:
```
foreach ($array as $key => $value) {
echo("Key is $key and Value is $value");
}
```
How can I do this in Javascript? I'm aware of:
```
for (x in array){
// Do something with x.
}
```
But I've found nothing that will replicate the php style foreach. Is it possible to concisely achieve something similar in Javascript? (I'm also using jQuery, if something can be done in jQuery). | First,
```
var array=[];
```
is preferable to using "new."
Second, your keys are numeric in this case, so you just do:
```
for (i=0;i<array.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
```
If you want to have keys that aren't numeric, use a JavaScript object instead of an array. It's valid to use strings instead of numbers as array indexes, but JavaScript doesn't have much support for that.
---
I use "console.log" because I assume you don't want a bunch of alerts popping up. console.log could be replaced with whatever you use to log info. You could use alert() or write text into a div instead. | Using [jQuery.each](http://docs.jquery.com/Utilities/jQuery.each) you could write something similar to (not tested):
```
jQuery.each(array, function(k,v) {
console.log("K: "+,k," V:",v);
});
``` | Looping through elements of an array in Javascript | [
"",
"javascript",
"jquery",
"arrays",
""
] |
I want to verify whether an e-mail is real or not. Some body told me I could do it with DNS check but I don't know how to do this.
Could somebody help me through this problem and I am developing with C#.
Thanks in advance. | I guess this code-project article gives you the information you want: [Effective Email Address Validation](http://www.codeproject.com/KB/validation/Valid_Email_Addresses.aspx)
But even if you confirm that a domain is valid, it is still not guaranteed that the email address/recipient is valid. E.g. "xyz@stackoverflow.com" -> the domain is valid, but "xyz" might not be a valid email address. | You can use DNS to determine if a *domain* is valid/resolving. That wouldn't necessarily mean that a given email address at that domain is valid. The only way to know that is to open an SMTP connection and try to send mail to that user. | E-Mail Existence Check in C# | [
"",
"c#",
""
] |
```
Regualar expression: <img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>
```
This works fine when 'src' is in lowercase and manages both single and double quotes.
I would like this expression to return matches for following test data
```
1. <html><img src ="kk.gif" alt="text"/></html>
2. <html><img Src ="kk.gif" alt="text"/></html>
3. <html><img sRC ="kk.gif" alt="text"/></html> (any charcter in 'src' can be uppercase/lowercase)
4. <html><img SRC ="kk.gif" alt="text"/></html>
5. <html><img src ='kk.gif' alt="text"/></html>
``` | Create the pattern with the CASE\_INSENSITIVE flag. See [`Pattern.compile(String, int)`](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#compile(java.lang.String,+int)). This will affect the entire string, which means the `img` also.
Or the cheap way, change `src` to `[Ss][Rr][Cc]`. This will just affect the `src` portion. | It seems to me that if you want to process HTML, the best way to go is to use a real HTML parser.
Although I am not familiar with Java, there seems to be quite a few to choose from: [Open Source HTML Parsers in Java](http://java-source.net/open-source/html-parsers).
This will allow you to deal with cases like an other attribute being before the src and including the character '>', which is valid HTML, or the src attribute including a quote, and probably a few other unlikely but possible trickeries. | How to change this regular expression to be case insenstive (looking for src tag) | [
"",
"java",
"regex",
""
] |
Does anybody know why JUnit 4 provides `assertEquals(foo,bar)` but not `assertNotEqual(foo,bar)` methods?
It provides `assertNotSame` (corresponding to `assertSame`) and `assertFalse` (corresponding to `assertTrue`), so it seems strange that they didn't bother including `assertNotEqual`.
By the way, I know that JUnit-addons provides the methods I'm looking for. I'm just asking out of curiosity. | I'd suggest you use the newer [`assertThat()`](http://junit.sourceforge.net/doc/ReleaseNotes4.4.html) style asserts, which can easily describe all kinds of negations and automatically build a description of what you expected and what you got if the assertion fails:
```
assertThat(objectUnderTest, is(not(someOtherObject)));
assertThat(objectUnderTest, not(someOtherObject));
assertThat(objectUnderTest, not(equalTo(someOtherObject)));
```
All three options are equivalent, choose the one you find most readable.
To use the simple names of the methods (and allow this tense syntax to work), you need these imports:
```
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
``` | There is an `assertNotEquals` in JUnit 4.11: <https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.11.md#improvements-to-assert-and-assume>
```
import static org.junit.Assert.assertNotEquals;
``` | Why doesn't JUnit provide assertNotEquals methods? | [
"",
"java",
"junit",
"assert",
""
] |
I'm trying to use document.getElementById().innerHTML in a JavaScript to change information in a webpage. On FireFox this works as described in the W3C documentation, however, the same method returns 'Unknown Error' in IE. The JavaScript looks like this:
```
function Change_Info (ID, ROW, VALUE)
{
if (document.getElementById)
{
var ntext = "<td width=4\% bgcolor=#FFFFFF> </td><td width=92\% bgcolor=#FFFFFF colspan=2><font face=Arial size=2 color=#5578C4>" + VALUE + "</font></td><td width=4\% bgcolor=#FFFFFF><center> </center></td>";
document.getElementById( ID + "-" + ROW).innerHTML = ntext;
return false;
}
}
```
The script is called by a MouseOver event like this:
```
onmouseover='Change_Info("thetag","1","Some Info");
```
The script would combine ID with a - and then ROW, which, in this example would be, thetag-1. The exact tag does exist in the html document. Using getElementById with the hardcoded tag name, reveils the same error, and the variable method is the prefered one in this situation.
To questions regarding why full html table information is in ntext, for whatever reason nested ID's fail on *both* FireFox and IE, even though the W3C specification states it should work (obviously both browsers have not fully implimented the W3C specs as persceribed). If someone knows of the way to access and change nested ID's, that works in both FireFox and IE, I'd sure like to know it.
Additionally, as yet I'm only getting this 'Unknown Error' in IE when using innerHTML to *change* the information. Reading works without error.
Can someone point out where my scripting error is so that I can swap text 'messages' on mouseover events. | IE does not let you add.alter table rows that way. You will need to use DOM Methods removeChild, appendChild, and createElement OR insertRow and insertCell | "Additionally, as yet I'm only getting this 'Unknown Error' in IE when using innerHTML to change the information. Reading works without error."
I faced the same problem and used the following:
```
var newdiv = document.createElement("div");
newdiv.innerHTML = "new content";
var container = document.getElementById("container");
container.removeChild( container.firstChild );
container.appendChild(newdiv);
```
<http://domscripting.com/blog/display/99> | document.getElementById().innerHTML fails with 'Unknown Error' in IE | [
"",
"javascript",
""
] |
I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible. | wsgi.input should be a file like stream object. You can read from that in blocks, and write those blocks directly to disk. That shouldn't use up any significant memory.
Or maybe I misunderstood the question? | If you use the cgi module to parse the input (which most frameworks use, e.g., Pylons, WebOb, CherryPy) then it will automatically save the uploaded file to a temporary file, and not load it into memory. | Upload a potentially huge textfile to a plain WSGI-server in Python | [
"",
"python",
"file",
"upload",
"wsgi",
""
] |
I'm using wxWidgets to write cross-plafrom applications. In one of applications I need to be able to load data from Microsoft Excel (.xls) files, but I need this to work on Linux as well, so I assume I cannot use OLE or whatever technology is available on Windows.
I see that there are many open source programs that can read excel files (OpenOffice, KOffice, etc.), so I wonder if there is some library that I could use?
Excel files it needs to support are very simple, straight tabular data. I don't need to extract any formatting except column/row position and the data itself. | I can say that I know of a wxWidgets application that reads Excel .xls and .xlsx files on any platform. For the .xlsx files we used an XML parser and zip stream reader and grab the data we need, pretty easy to get going. For the .xls files we used: [ExcelFormat](http://www.codeproject.com/KB/office/ExcelFormat.aspx), which works well and we found the author to be very generous with his support.
Maybe just some encouragement to give it a go? It was a couple of days work to get working. | Suggestedd reference: [What is a simple and reliable C library for working with Excel files?](https://stackoverflow.com/questions/493111/what-is-the-best-c-library-that-can-access-excel-files)
I came across other libraries (chicago on sf.net, xlsLib) but they seem to be outdated.
jrh | Load Excel data into Linux / wxWidgets C++ application? | [
"",
"c++",
"excel",
"wxwidgets",
""
] |
Lets say that input from the user is a decimal number, ex. 5.**2155** (having 4 decimal digits). It can be stored freely (int,double) etc.
Is there any **clever** (or very simple) way to find out how many decimals the number has? (kinda like the question how do you find that a number is even or odd by masking last bit). | Two ways I know of, neither very clever unfortunately but this is more a limitation of the environment rather than me :-)
The first is to `sprintf` the number to a big buffer with a `"%.50f"` format string, strip off the trailing zeros then count the characters after the decimal point. This will be limited by the `printf` family itself. Or you could use the string as input by the user (rather than `sprintf`ing a floating point value), so as to avoid floating point problems altogether.
The second is to subtract the integer portion then iteratively multiply by 10 and again subtract the integer portion until you get zero. This is limited by the limits of computer representation of floating point numbers - at each stage you may get the problem of a number that cannot be represented exactly (so .2155 may actually be .215499999998). Something like the following (untested, except in my head, which is about on par with a COMX-35):
```
count = 0
num = abs(num)
num = num - int(num)
while num != 0:
num = num * 10
count = count + 1
num = num - int(num)
```
If you know the sort of numbers you'll get (e.g., they'll all be 0 to 4 digits after the decimal point), you can use standard floating point "tricks" to do it properly. For example, instead of:
```
while num != 0:
```
use
```
while abs(num) >= 0.0000001:
``` | Once the number is converted from the user representation (string, OCR-ed gif file, whatever) into a floating point number, you are not dealing with the same number necessarily. So the strict, not very useful answer is "No".
If (**case A**) you can avoid converting the number from the string representation, the problem becomes much easier, you only need to count the digits after the decimal point and subtract the number of trailing zeros.
If you cannot do it (**case B**), then you need to make an assumption about the maximum number of decimals, convert the number back into string representation and round it to this maximum number using the [round-to-even method](http://en.wikipedia.org/wiki/Rounding#Round-to-even_method). For example, if the user supplies 1.1 which gets represented as 1.09999999999999 (hypothetically), converting it back to string yields, guess what, "1.09999999999999". Rounding this number to, say, four decimal points gives you "1.1000". Now it's back to **case A**. | C/C++ counting the number of decimals? | [
"",
"c++",
"c",
"decimal",
""
] |
This is a very newbie question and i will probably get downvoted for it, but i quite honestly couldn't find the answer after at least an hour googling. I learned how to slice strings based on "exact locations" where you have to know exactly where the word ends. But i did not find any article that explained how do it on "non static" strings that could change.
Also i do not want to use string.split() in this case as its a little overkill for what i need.
I basically have a string like this:
```
myString = "!save python Python is a high-level object oriented language created by Guido van Rossum."
# the format is !save [singleword] [definition]
```
i need to "slice" this string but i cant figure out a proper way to do it.
i need to save a to variable the title (python in this case) and the definition of this string. Somethig like:
```
title = myString[1]
definition = myString[everything after string[1]
```
I'm not exactly sure how to do this when you have a dynamic string where you dont know where each word ends.
I would greatly appreciate some pointers on what functions/methods should i read on to archieve this. Thank you in advance. | Why is split overkill?
```
verb, title, definition = myString.split (' ', 2)
``` | If you have spaces between your command, title, and definition you could:
```
wordList = myString.split()
cmd = wordList[0] # !save
title = wordList[1] # python
definition = ' '.join(wordList[2:]) # Python is a high-level object oriented language created by Guido van Rossum.
```
If you really would rather not use split you could use regular expressions:
```
import re
m = re.match('(/S+)/s*(/S+)/s*(.*)')
cmd = m.group(1)
title = m.group(2)
definition = m.group(3)
``` | Need some help with python string / slicing operations | [
"",
"python",
"string",
"slice",
""
] |
I have a situation in C# where I have a list of simple types. This list can be accessed by multiple threads: entries can be added or removed, and the existence of an entry can be checked. I have encapsulated the list in an object exposing just those three operations so far.
I have a few cases to handle (not exactly the same as the methods I just mentioned).
1. A thread can just check for the existence of an entry. (simple)
2. A thread can check for the existence of an entry, and if it doesn't exist, add it.
3. A thread needs to check whether an entry exists, and if it does, wait until it is removed.
4. A combination of 2 and 3, where a thread checks for the existence of an entry, if it does exist, it must wait until it is removed before it can then add it itself.
The whole idea is that the existence of an entry signifies a lock. If an entry exists, the object it identifies cannot be changed and code cannot proceed because it is being modified elsewhere.
These may seem like simple novice situations but I'm refreshing myself on concurrency issues and it's making me a bit paranoid, and I'm also not as familiar with C#'s concurrency mechanisms.
What would be the best way to handle this? Am I totally off? Should check and add (test and set?) be combined into a fourth atomic operation? Would I simply be adding lock blocks to my methods where the list is accessed?
Also, is it possible to unit test this kind of thing (not the simple operations, the concurrency situations)? | Unit testing will certainly be hard.
This can all be done reasonably simply with the "native" concurrency mechanisms in .NET: lock statements and `Monitor.Wait`/`Monitor.PulseAll`. Unless you have a separate monitor per item though, you're going to need to wake all the threads up whenever anything is removed - otherwise you won't be able to tell the "right" thread to wake up.
If it really is just a *set* of items, you might want to use `HashSet<T>` instead of `List<T>` to represent the collection, by the way - nothing you've mentioned is to do with ordering.
Sample code, assuming that a set is okay for you:
```
using System;
using System.Collections.Generic;
using System.Threading;
public class LockCollection<T>
{
private readonly HashSet<T> items = new HashSet<T>();
private readonly object padlock = new object();
public bool Contains(T item)
{
lock (padlock)
{
return items.Contains(item);
}
}
public bool Add(T item)
{
lock (padlock)
{
// HashSet<T>.Add does what you want already :)
// Note that it will return true if the item
// *was* added (i.e. !Contains(item))
return items.Add(item);
}
}
public void WaitForNonExistence(T item)
{
lock (padlock)
{
while (items.Contains(item))
{
Monitor.Wait(padlock);
}
}
}
public void WaitForAndAdd(T item)
{
lock (padlock)
{
WaitForNonExistence(item);
items.Add(item);
}
}
public void Remove(T item)
{
lock (padlock)
{
if (items.Remove(item))
{
Monitor.PulseAll(padlock);
}
}
}
}
```
(Completely untested, admittedly. You might also want to specify timeouts for the waiting code...) | While #1 may be the simplest to write, it's essentially a useless method. Unless you are holding onto the same lock after finishing a query for "existence of an entry", you are actually returning "existence of an entry at some point in the past". It doesn't give you any information about the current existence of the entry.
In between the discovery of a value in the list then doing any operation to retrieve, remove the value, another thread could come and remove it for you.
Contains operations on a concurrent list should be combined with the operation you plan on doing in the case of true/false existence of that check. For instance TestAdd() or TestRemove() is **much** safer than Contains + Add or Contains + Remove | C# Concurrent List Questions | [
"",
"c#",
"concurrency",
""
] |
I created an App with ASP.NET MVC 1.0 and wish to use a custom method (for admins) to create a user. I took the Register method (in the Account controller) and renamed it to Create. I then commented out the line **FormsAuth.SignIn(userName, false);** to avoid the newly created user to sign in.
When I complete the create user form, the user gets added fine, but he also gets signed in. Now both me and the new user are signed in. I know this because my ListUsers page tests for **user.IsOnline**
UPDATE (2009-07-15 14:40): I have been doing some Google-ing and found that User.IsOnline is not very reliable due to the stateless HTTP protocol. Note: if I go to the UserDetails page (which is populated using MembershipUserAndRolesViewData) the Last Login shows as NULL. But my ListUsers page shows a login date...???
```
public class AccountController : Controller
{
// ...
[Authorize(Roles = "Administrator")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string userName, string email, string password, string confirmPassword)
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
if (ValidateRegistration(userName, email, password, confirmPassword))
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);
if (createStatus == MembershipCreateStatus.Success)
{
//FormsAuth.SignIn(userName, false); // createPersistentCookie
return RedirectToAction("ListUsers", "Account");
}
else
{
ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View();
}
}
``` | Checking <http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.isonline.aspx> mentions this:
> A user is considered online if the current date and time minus the UserIsOnlineTimeWindow property value is earlier than the LastActivityDate for the user.
>
> The LastActivityDate for a user is updated to the current date and time by the CreateUser, UpdateUser and ValidateUser methods, and can be updated by some of the overloads of the GetUser method.
This page <http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.lastactivitydate.aspx> also says this:
> The LastActivityDate for a user is updated to the current date and time by the CreateUser and ValidateUser methods, and can be updated by some overloads of the GetUser method. You can use the UpdateUser method to set the LastActivityDate property to a specific date and time.
So it seems that when you create a new account, this is considered as being "Online".
A workaround could be to modify the default `CreateUser` in the `AccountMembershipService` class to reset the date when you create an account:
```
public MembershipCreateStatus CreateUser(string userName, string password, string email)
{
MembershipCreateStatus status;
MembershipUser user = _provider.CreateUser(userName, password, email, null, null, true, null, out status);
user.LastActivityDate = DateTime.MinValue; //set the LastActivityDate to a point far back in the past
_provider.UpdateUser(user); //update the user to the MembershipProvider
return status;
}
``` | There must be something wrong with a code you didn't show. If you create a new ASP.NET MVC project using the default VS template and then comment out the line `FormsAuth.SignIn(userName, false)` the user is not signed in as expected. | How to stop MembershipService.CreateUser() from auto login on ASP.NET MVC? | [
"",
"c#",
"asp.net-mvc",
""
] |
For our deployments, I just want to drop the existing stored proc, then re-create in the same script. The script wizard only seeems to give me a mutually exclusive option - I'm looking for a Drop-Then Create Option. Am I missing something?
[script wizard http://img37.imageshack.us/img37/7167/scriptwizard.png](http://img37.imageshack.us/img37/7167/scriptwizard.png) | Its a [bug](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=260519). It appears to be fixed after I installed SQL Server SP1. Appears they have just added a single drop down called script drops - which makes a heck of a lot more sense than an option to "only script drops". | Wizards are just a helper and sometimes don't give you options for all the possibilities. You could use the wizard to create both scripts and then copy paste them together. | IN SSMS how do I script a stored proc with a Drop Section and a Create Section? | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
We've created an intranet site that requires the same password as the user's network login, so we use LDAP to check the username/password.
That's fine, but if they enter it incorrectly three times it locks their account out, and one or two users have found this confusing.
Is there anyway at all I could check, using LDAP/PHP whether or not their account is locked, so I can display a little message prompting them to contact IT? | You need to connect to the LDAP using the LDAP functions in PHP and perform search/read to locate and get the information. You can read about it here: <https://www.php.net/manual/en/book.ldap.php>
Find a sample code for reading entries:
```
if (!($ldap=ldap_connect($ldapip, $ldapport)))
{
die("Error:Unable to connect to the LDAP Server");
return;
}
if (!ldap_bind($ldap, $admindn, $adminpwd))
{
die("Error:Unable to bind to '$dn'!");
return;
}
$sr=ldap_search($ldap, $userbasedn, $filter);
$info = ldap_get_entries($ldap, $sr);
if($info["count"] > 0)
{
$entry = ldap_first_entry($ldap, $sr);
$return_array = ldap_get_attributes($ldap, $entry);
if($return_array)
{
for ($i=0;$i<$return_array['count'];$i++)
{
print($return_array[$i]);
print($return_array[$return_array[$i]][0]);
}
}
}
```
You might want to check for the fields lockoutTime in AD, nsaccountlock in LDAP and read them | One of AD profile attribute `useraccountcontrol`.
This contains `decimal` value which can be converted into readable here;
* <https://support.microsoft.com/en-us/kb/305144>
* <http://ananthdeodhar.com/php-active-directory-integration-get-useraccountcontrol-attributes/>
Locked can be referring to multiple cases, normally
* `ACCOUNTDISABLE` 2 / 0x0002 (hexa)
* `PASSWORD_EXPIRED` 8388608 / 0x800000
* `LOCKOUT` 16 / 0x0010 | How to check if a user account is locked via PHP/LDAP? | [
"",
"php",
"ldap",
""
] |
I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.
Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.
How do I verify a certificate in Python? | From release version 2.7.9/3.4.3 on, Python **by default** attempts to perform certificate validation.
This has been proposed in PEP 467, which is worth a read: <https://www.python.org/dev/peps/pep-0476/>
The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).
Relevant documentation:
<https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection>
> This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl.\_create\_unverified\_context() can be passed to the context parameter.
<https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection>
> Changed in version 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl.\_create\_unverified\_context() can be passed to the context parameter.
Note that the new built-in verification is based on the *system-provided* certificate database. Opposed to that, the [requests](http://docs.python-requests.org) package ships its own certificate bundle. Pros and cons of both approaches are discussed in the [*Trust database* section of PEP 476](https://www.python.org/dev/peps/pep-0476/#trust-database). | I have added a distribution to the Python Package Index which makes the `match_hostname()` function from the Python 3.2 `ssl` package available on previous versions of Python.
<http://pypi.python.org/pypi/backports.ssl_match_hostname/>
You can install it with:
```
pip install backports.ssl_match_hostname
```
Or you can make it a dependency listed in your project's `setup.py`. Either way, it can be used like this:
```
from backports.ssl_match_hostname import match_hostname, CertificateError
...
sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
try:
match_hostname(sslsock.getpeercert(), hostname)
except CertificateError, ce:
...
``` | Validate SSL certificates with Python | [
"",
"python",
""
] |
I'm trying to create thumbnails for uploaded images in a JRuby/Rails app using the Image Voodoo plugin - the problem is the resized thumbnails look like... ass.
It seems that the code to generate the thumbnails is absolutely doing everything correctly to set the interpolation rendering hint to "bicubic", but it isn't honoring them on our dev environment (OS X), or on the production web server (Linux).
I've extracted out the code to generate the thumbnails, rewritten it as a straight Java app (ie kicked off from a main() method) with the interpolation rendering hint explicitly set to "bicubic", and have reproduced the (lack of) bicubic and bilinear resizing.
As expected on both OS X and Linux the thumbanils are ugly and pixelated, but on Windows, it resizes the images nicely with bicubic interpolation used.
Is there any JVM environment setting and/or additional libraries that I'm missing to make it work? I'm doing a lot of banging of head against wall for this one. | I realize this question was asked a while ago, but incase anyone else is still running into this.
The reason the thumbnails look like ass are caused by two things (primarily the first one):
* Non-incremental image scaling in Java is very rough, throws a lot of pixel data out and averages the result once regardless of the rendering hint.
* Processing a poorly supported BufferedImage type in Java2D (typically GIFs) can result in very poor looking/dithered results.
As it turns out the old [AreaAveragingScaleFilter](http://download.oracle.com/javase/6/docs/api/java/awt/image/AreaAveragingScaleFilter.html) does a decent job of making good looking thumbnails, but it is slow and deprecated by the Java2D team -- unfortunately they didn't replace it with any nice out-of-the-box alternative and left us sort of on our own.
Chris Campbell (from the Java2D team) addressed this a few years ago with the concept of incremental scaling -- instead of going from your starting resolution to the target resolution in one operation, you do it in steps, and the result looks much better.
Given that the code for this is decently large, I wrote all the best-practices up into a library called [imgscalr](http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/) and released it under the Apache 2 license.
The most basic usage looks like this:
```
BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, 640);
```
In this use-case the library uses what is called it's "automatic" scaling mode and will fit the resulting image (honoring it's proportions) within a bounding box of 640x640. So if the image is not a square and is a standard 4:3 image, it will resize it to 640x480 -- the argument is just it's largest dimension.
There are a slew of other methods on the [Scalr class](http://www.thebuzzmedia.com/downloads/software/imgscalr/javadoc/org/imgscalr/Scalr.html) (all static and easy to use) that allow you to control everything.
For the best looking thumbnails possible, the command would look like this:
```
BufferedImage img = ImageIO.read(...); // load image
BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY,
150, 100, Scalr.OP_ANTIALIAS);
```
The Scalr.OP\_ANTIALIAS is optional, but a lot of users feel that when you scale down to a small enough thumbnail in Java, some of the transitions between pixel values are a little too discrete and make the image look "sharp", so a lot of users asked for a way to soften the thumbnail a bit.
That is done through a [ConvolveOp](http://download.oracle.com/javase/6/docs/api/java/awt/image/ConvolveOp.html) and if you have never used them before, trying to figure out the right "kernel" to use is... a pain in the ass. That OP\_ANTIALIAS constant defined on the class it the best looking anti-aliasing op I found after a week of testing with another user who had deployed imgscalr into their social network in Brazil (used to scale the profile photos). I included it to make everyone's life a bit easier.
Also, ontop of all these examples, you might have noticed when you scale GIFs and some other types of images (BMPs) that sometimes the scaled result looks TERRIBLE compared to the original... that is because of the image being in a poorly supported BufferedImage type and Java2D falling back to using it's software rendering pipeline instead of the hardware accelerated one for better supported image types.
imgscalr will take care of all of that for you and keep the image in the best supported image type possible to avoid that.
Anyway, that is a REALLY long way of saying "You can use imgscalr to do all that for you and not have to worry about anything". | maybe is this a solution for you:
```
public BufferedImage resizeImage(BufferedImage source, int width, int height)
{
BufferedImage result = new BufferedImage(widht, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = result.getGraphics();
g.drawImage(source, 0, 0, widht, height, null);
g.dispose();
return result;
}
``` | Java 2D Image resize ignoring bicubic/bilinear interpolation rendering hints (OS X + linux) | [
"",
"java",
"image",
"resize",
"2d",
"bicubic",
""
] |
I have an SQL Server 2005 table that has a varchar(250) field which contains keywords that I will use for searching purposes. I can't change the design. The data looks like this...
> Personal, Property, Cost, Endorsement
What is the most efficient way to run search queries against these keywords? The only thing I can think of is this...
```
WHERE Keywords LIKE '%endorse%'
``` | Since normalization is not an option, the next best option is going to be to configure and use Full Text Search. This will maintain an internal search index that will make it very easy for you to search within your data.
The problem with solutions like LIKE '%pattern%' is that this will produce a full table scan (or maybe a full index scan) that could produce locks on a large amount of the data in your table, which will slow down any operations that hit the table in question. | the most efficient way is to normalize your db design. never store CSV values into a single cell.
other than using like you might consider full text search. | Efficient way to Query a Delimited Varchar Field in SQL | [
"",
"sql",
""
] |
Is it possible to kill a Java thread without raising an exception in it?
This is just for testing purposes - I want to simulate a case when the entire computer dies mid-thread.
Note - I saw a deprecated `Thread.destroy()` method, but the documentation says it never got implemented in the first place. | No. There is the deprecated, 'inherently unsafe' `Thread.stop()` method, but as its comment emphasizes, things could be left in an deeply corrupted state, and the ThreadDeath Error is still thrown inside the thread.
Sun's explanation of the problems with `stop()`, which can manifest long after it appears to work, is at:
<http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html>
Wouldn't killing the JVM process (or yanking the plug) be a better simulation of computer death? | There is no portable method. You might try to call "kill -9" (or your local equivalent) on the whole java process, if you want to suppress the running of finalizers and shutdown hooks.
You won't get any kind of repeatable results out of such a test, but it might be interesting to perform such tests a few thousand times if your program is writing to the file system or a database and might leave inconsistent data structures when being killed. | Killing thread instantly in Java | [
"",
"java",
"multithreading",
"kill",
""
] |
simple question really, i was wanting to know what naming conventions anybody puts on there DTO / POCOS ....
I didn't really want to prefix like hungarian notation.. i got away from that!.
But my dtos naming are clashing with my actual returned object names and although they are in a different namespace its still a bit confusing..
I was wondering what naming conventions anybody applies to it
for example my customer object is called Customer
and i do a mapping to dto ... which is Customer.. iwas thinking DtoCustomer ..
Not sure
Anyone ? | I prefer to use namespaces for this. Using namespace aliases for this makes it even more clear.
This would make code that looks like:
```
Customer myCustomer = new Customer();
Dto.Customer dtoCustomer = ....;
```
If I'm working entirely in the DTO layer, I still can work with "Customer" at this point. | In my experience, DTO's are often subsets or aggregations of data that your domain entities represent. This is usually because domain entities are rich, highly inter-related, complex objects that have both behavior and data. As such, I try to name my DTO's to reflect as much as possible the subset of information they represent. In the case of customers, I often have DTO's that are fine-tuned to the information being requested:
* CustomerHeader
* CustomerDetail
* CustomerWithRecentOrders
* CustomerAndBill
In the examples above, CustomerHeader would likely only contain the customer ID and Name, often used to display customers in simple lists. CustomerDetail would contain most customer information, but wouldn't contain any of the relational properties that a full blown Customer entity is likely to contain. The others should be self explanatory, which is the ultimate goal. | prefixing DTO / POCOS - naming conventions? | [
"",
"c#",
"naming-conventions",
"poco",
"dto",
""
] |
Is there a way to overload the event += and -= operators in C#? What I want to do is take an event listener and register it to different events. So something like this:
```
SomeEvent += new Event(EventMethod);
```
Then instead of attaching to SomeEvent, it actually attaches to different events:
```
DifferentEvent += (the listener above);
AnotherDiffEvent += (the listener above);
```
Thanks | It's not really overloading, but here is how you do it:
```
public event MyDelegate SomeEvent
{
add
{
DifferentEvent += value;
AnotherDiffEvent += value;
}
remove
{
DifferentEvent -= value;
AnotherDiffEvent-= value;
}
}
```
More information on this on [switchonthecode.com](http://www.switchonthecode.com/tutorials/csharp-tutorial-event-accessors) | You can do this In C# using [**custom event accessors**](http://msdn.microsoft.com/en-us/library/bb882534.aspx).
```
public EventHandler DiffEvent;
public EventHandler AnotherDiffEvent;
public event EventHandler SomeEvent
{
add
{
DiffEvent += value;
AnotherDiffEvent += value;
}
remove
{
DiffEvent -= value;
AnotherDiffEvent -= value;
}
}
```
Which means you can simply call `SomeEvent += new EventHandler(Foo)` or `SomeEvent -= new EventHandler(Foo)` and the appropiate event handlers will be added/removed automatically. | Overload the += event operator | [
"",
"c#",
"events",
"operator-overloading",
"overloading",
"event-listener",
""
] |
I was pretty sure the answer was **NO**, and hence google gears, adobe AIR, etc.
If I was right, then how does <http://tiddlywiki.com> work? It is persistent and written in javascript. It is also just a single HTML file that has no external (serverside) dependencies. WTF? Where/how does it store its state? | Tiddlywiki has several methods of saving data, depending on which browser is used. [As you could see in the source](https://github.com/TiddlyWiki/tiddlywiki/blob/master/js/FileSystem.js#L21).
* If ActiveX is enabled, it uses Scripting.FileSystemObject.
* On Gecko-based browsers, it tries to use UniversalXPConnect.
* If Java is enabled, it uses the TiddlySaver Java applet.
* If [Java LiveConnect](https://developer.mozilla.org/en/LiveConnect) is enabled, it tries to use Java's file classes. | HTML5's File[[1](http://dev.w3.org/2006/webapi/FileAPI/)], FileWriter[[2](http://dev.w3.org/2009/dap/file-system/file-dir-sys.html)], and FileSystem[[3](http://dev.w3.org/2009/dap/file-system/file-writer.html)] APIs are available in the latest Developer channel of Google Chrome. The FileSystem API lets you read/write to a sandbox filesystem within a space the browser knows about. You cannot, for example, open 'My Pictures' folder on the user's local FS and read/write to that. That's something in the works, but it won't be ready for a while. Example of writing a file:
```
window.requestFileSystem(
TEMPORARY, // persistent vs. temporary storage
1024 * 1024, // 1MB. Size (bytes) of needed space
initFs, // success callback
opt_errorHandler // opt. error callback, denial of access
);
function initFs(fs) {
fs.root.getFile('logFile.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) { // FileWriter
writer.onwrite = function(e) {
console.log('Write completed.');
};
writer.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
var bb = new BlobBuilder();
bb.append('Lorem ipsum');
writer.write(bb.getBlob('text/plain'));
}, errorHandler);
}
}
```
Check out this [HTML5 Storage slide deck](http://html5-demos.appspot.com/static/html5storage/index.html#slide44) for more code snippets. | Can javascript access a filesystem? | [
"",
"javascript",
"persistence",
"tiddlywiki",
""
] |
I have my program that can draw rectangles. I have two problems I can't solve. After I draw the rectangle it won't stay. The only code I have that clears the canvas in under paint, repaint is only called on mouse drag. Why when I mouse release or mouse move does my canvas clear. The second thing isn't as much a problem, but something I can't figure out, when either the height or width of my rectangle is negative the rectangle is filled in black.
```
package pracpapp2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseTracker4July extends JFrame
implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private JLabel mousePosition;
int x, y;
int x1, x2, y1, y2;
int w, h;
private JLabel recStart;
private JLabel recStop;
private JLabel cords;
// set up GUI and register mouse event handlers
public MouseTracker4July()
{
super( "Rectangle Drawer" );
mousePosition = new JLabel();
mousePosition.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add( mousePosition, BorderLayout.CENTER );
JLabel text1 = new JLabel();
text1.setText( "At the center the mouse pointer's coordinates will be displayed." );
getContentPane().add( text1, BorderLayout.SOUTH );
recStart = new JLabel();
getContentPane().add(recStart, BorderLayout.WEST);
recStop = new JLabel();
getContentPane().add(recStop, BorderLayout.EAST);
cords = new JLabel();
getContentPane().add(cords, BorderLayout.NORTH);
addMouseListener( this ); // listens for own mouse and
addMouseMotionListener( this ); // mouse-motion events
setSize( 800, 600 );
setVisible( true );
}
// MouseListener event handlers
// handle event when mouse released immediately after press
public void mouseClicked( MouseEvent event )
{
mousePosition.setText( "Clicked at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse pressed
public void mousePressed( MouseEvent event )
{
mousePosition.setText( "Pressed at [" +(x1 = event.getX()) +
", " + (y1 = event.getY()) + "]" );
recStart.setText( "Start: [" + x1 +
", " + y1 + "]" );
}
// handle event when mouse released after dragging
public void mouseReleased( MouseEvent event )
{
mousePosition.setText( "Released at [" +(x2 = event.getX()) +
", " + (y2 = event.getY()) + "]" );
recStop.setText( "End: [" + x2 +
", " + y2 + "]" );
}
// handle event when mouse enters area
public void mouseEntered( MouseEvent event )
{
mousePosition.setText( "Mouse entered at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse exits area
public void mouseExited( MouseEvent event )
{
mousePosition.setText( "Mouse outside window" );
}
// MouseMotionListener event handlers
// handle event when user drags mouse with button pressed
public void mouseDragged( MouseEvent event )
{
mousePosition.setText( "Dragged at [" + (x = event.getX()) +
", " + (y = event.getY()) + "]" );
// call repaint which calls paint
repaint();
}
// handle event when user moves mouse
public void mouseMoved( MouseEvent event )
{
mousePosition.setText( "Moved at [" + event.getX() +
", " + event.getY() + "]" );
}
public void paint(Graphics g)
{
super.paint(g); // clear the frame surface
g.drawString("Start Rec Here", x1, y1);
g.drawString("End Rec Here", x, y);
w = x1 - x;
h = y1 - y;
w = w * -1;
h = h * -1;
g.drawRect(x1, y1, w, h);
cords.setText( "w = " + w + ", h = " + h);
}
public static void main( String args[] )
{
MouseTracker4July application = new MouseTracker4July();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MouseTracker
``` | Ok, after re-reading your question it seems you could care less to have multiple rectangles :)
Here is a solution with only one at a time (which is close to what you had to begin with):
```
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class MouseTracker4July extends JFrame implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private final JLabel mousePosition;
int x1, x2, y1, y2;
int x, y, w, h;
private final JLabel recStart;
private final JLabel recStop;
private final JLabel cords; // set up GUI and register mouse event handlers
boolean isNewRect = true;
public MouseTracker4July() {
super( "Rectangle Drawer" );
this.mousePosition = new JLabel();
this.mousePosition.setHorizontalAlignment( SwingConstants.CENTER );
getContentPane().add( this.mousePosition, BorderLayout.CENTER );
JLabel text1 = new JLabel();
text1.setText( "At the center the mouse pointer's coordinates will be displayed." );
getContentPane().add( text1, BorderLayout.SOUTH );
this.recStart = new JLabel();
getContentPane().add( this.recStart, BorderLayout.WEST );
this.recStop = new JLabel();
getContentPane().add( this.recStop, BorderLayout.EAST );
this.cords = new JLabel();
getContentPane().add( this.cords, BorderLayout.NORTH );
addMouseListener( this ); // listens for own mouse and
addMouseMotionListener( this ); // mouse-motion events
setSize( 800, 600 );
setVisible( true );
}
// MouseListener event handlers // handle event when mouse released immediately after press
public void mouseClicked( final MouseEvent event ) {
this.mousePosition.setText( "Clicked at [" + event.getX() + ", " + event.getY() + "]" );
repaint();
}
// handle event when mouse pressed
public void mousePressed( final MouseEvent event ) {
this.mousePosition.setText( "Pressed at [" + ( this.x1 = event.getX() ) + ", " + ( this.y1 = event.getY() ) + "]" );
this.recStart.setText( "Start: [" + this.x1 + ", " + this.y1 + "]" );
this.isNewRect = true;
repaint();
}
// handle event when mouse released after dragging
public void mouseReleased( final MouseEvent event ) {
this.mousePosition.setText( "Released at [" + ( this.x2 = event.getX() ) + ", " + ( this.y2 = event.getY() ) + "]" );
this.recStop.setText( "End: [" + this.x2 + ", " + this.y2 + "]" );
repaint();
}
// handle event when mouse enters area
public void mouseEntered( final MouseEvent event ) {
this.mousePosition.setText( "Mouse entered at [" + event.getX() + ", " + event.getY() + "]" );
repaint();
}
// handle event when mouse exits area
public void mouseExited( final MouseEvent event ) {
this.mousePosition.setText( "Mouse outside window" );
repaint();
}
// MouseMotionListener event handlers // handle event when user drags mouse with button pressed
public void mouseDragged( final MouseEvent event ) {
this.mousePosition.setText( "Dragged at [" + ( this.x2 = event.getX() ) + ", " + ( this.y2 = event.getY() ) + "]" ); // call repaint which calls paint repaint();
this.isNewRect = false;
repaint();
}
// handle event when user moves mouse
public void mouseMoved( final MouseEvent event ) {
this.mousePosition.setText( "Moved at [" + event.getX() + ", " + event.getY() + "]" );
repaint();
}
@Override
public void paint( final Graphics g ) {
super.paint( g ); // clear the frame surface
g.drawString( "Start Rec Here", this.x1, this.y1 );
g.drawString( "End Rec Here", this.x2, this.y2 );
int width = this.x1 - this.x2;
int height = this.y1 - this.y2;
this.w = Math.abs( width );
this.h = Math.abs( height );
this.x = width < 0 ? this.x1
: this.x2;
this.y = height < 0 ? this.y1
: this.y2;
if ( !this.isNewRect ) {
g.drawRect( this.x, this.y, this.w, this.h );
}
this.cords.setText( "w = " + this.w + ", h = " + this.h );
}
public static void main( final String args[] ) {
MouseTracker4July application = new MouseTracker4July();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MouseTracker
``` | You need to store your drawn items in some data structure and ensure that each item in the structure is painted to the canvas on repaint.
Also, you need to add repaint to each of your mouse events.
Like this: (this assumes you want to keep ALL rect's) - you can go with a single rect by eliminating the arraylist and replacing with a single rect instance.
```
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class MouseTracker4July extends JFrame implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private final JLabel mousePosition;
int x1, x2, y1, y2;
int w, h;
private final JLabel recStart;
private final JLabel recStop;
private final JLabel cords; // set up GUI and register mouse event handlers
private final ArrayList< Rectangle > rectangles = new ArrayList< Rectangle >();
private boolean isNewRect = true;
public MouseTracker4July() {
super( "Rectangle Drawer" );
this.mousePosition = new JLabel();
this.mousePosition.setHorizontalAlignment( SwingConstants.CENTER );
getContentPane().add( this.mousePosition, BorderLayout.CENTER );
JLabel text1 = new JLabel();
text1.setText( "At the center the mouse pointer's coordinates will be displayed." );
getContentPane().add( text1, BorderLayout.SOUTH );
this.recStart = new JLabel();
getContentPane().add( this.recStart, BorderLayout.WEST );
this.recStop = new JLabel();
getContentPane().add( this.recStop, BorderLayout.EAST );
this.cords = new JLabel();
getContentPane().add( this.cords, BorderLayout.NORTH );
addMouseListener( this ); // listens for own mouse and
addMouseMotionListener( this ); // mouse-motion events
setSize( 800, 600 );
setVisible( true );
}
// MouseListener event handlers // handle event when mouse released immediately after press
public void mouseClicked( final MouseEvent event ) {
this.mousePosition.setText( "Clicked at [" + event.getX() + ", " + event.getY() + "]" );
repaint();
}
// handle event when mouse pressed
public void mousePressed( final MouseEvent event ) {
this.mousePosition.setText( "Pressed at [" + ( this.x1 = event.getX() ) + ", " + ( this.y1 = event.getY() ) + "]" );
this.recStart.setText( "Start: [" + this.x1 + ", " + this.y1 + "]" );
repaint();
}
// handle event when mouse released after dragging
public void mouseReleased( final MouseEvent event ) {
this.mousePosition.setText( "Released at [" + ( this.x2 = event.getX() ) + ", " + ( this.y2 = event.getY() ) + "]" );
this.recStop.setText( "End: [" + this.x2 + ", " + this.y2 + "]" );
Rectangle rectangle = getRectangleFromPoints();
this.rectangles.add( rectangle );
this.w = this.h = this.x1 = this.y1 = this.x2 = this.y2 = 0;
this.isNewRect = true;
repaint();
}
private Rectangle getRectangleFromPoints() {
int width = this.x1 - this.x2;
int height = this.y1 - this.y2;
Rectangle rectangle = new Rectangle( width < 0 ? this.x1
: this.x2, height < 0 ? this.y1
: this.y2, Math.abs( width ), Math.abs( height ) );
return rectangle;
}
// handle event when mouse enters area
public void mouseEntered( final MouseEvent event ) {
this.mousePosition.setText( "Mouse entered at [" + event.getX() + ", " + event.getY() + "]" );
repaint();
}
// handle event when mouse exits area
public void mouseExited( final MouseEvent event ) {
this.mousePosition.setText( "Mouse outside window" );
repaint();
}
// MouseMotionListener event handlers // handle event when user drags mouse with button pressed
public void mouseDragged( final MouseEvent event ) {
this.mousePosition.setText( "Dragged at [" + ( this.x2 = event.getX() ) + ", " + ( this.y2 = event.getY() ) + "]" ); // call repaint which calls paint repaint();
this.isNewRect = false;
repaint();
}
// handle event when user moves mouse
public void mouseMoved( final MouseEvent event ) {
this.mousePosition.setText( "Moved at [" + event.getX() + ", " + event.getY() + "]" );
repaint();
}
@Override
public void paint( final Graphics g ) {
super.paint( g ); // clear the frame surface
g.drawString( "Start Rec Here", this.x1, this.y1 );
g.drawString( "End Rec Here", this.x2, this.y2 );
Rectangle newRectangle = getRectangleFromPoints();
if ( !this.isNewRect ) {
g.drawRect( newRectangle.x, newRectangle.y, newRectangle.width, newRectangle.height );
}
for( Rectangle rectangle : this.rectangles ) {
g.drawRect( rectangle.x, rectangle.y, rectangle.width, rectangle.height );
}
this.cords.setText( "w = " + this.w + ", h = " + this.h );
}
public static void main( final String args[] ) {
MouseTracker4July application = new MouseTracker4July();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MouseTracker
``` | How to draw a rectangle on a java applet using mouse drag event and make it stay | [
"",
"java",
"swing",
"drawing",
"mouseevent",
""
] |
There is an `eval()` function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. What could an example be? | `eval` and `exec` are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &c.
For example, if I had to deal with such dynamic Python sources, I'd reach for the [ast](http://docs.python.org/library/ast.html#module-ast) module -- `ast.literal_eval` is MUCH safer than `eval` (you can call it directly on a string form of the expression, if it's a one-off and relies on simple constants only, or do `node = ast.parse(source)` first, then keep the `node` around, perhaps munge it with suitable visitors e.g. for variable lookup, then `literal_eval` the node) -- or, once having put the node in proper shape and vetted it for security issues, I could `compile` it (yielding a code object) and build a new function object out of that. Far less simple (except that `ast.literal_eval` is just as simple as `eval` for the simplest cases!) but safer and preferable in production-quality code.
For many tasks I've seen people (ab-)use `exec` and `eval` for, Python's powerful built-ins, such as `getattr` and `setattr`, indexing into `globals()`, &c, provide preferable and in fact often simpler solutions. For specific uses such as parsing JSON, library modules such as `json` are better (e.g. see SilentGhost's comment on tinnitus' answer to this very question). Etc, etc... | The [Wikipedia article on `eval`](http://en.wikipedia.org/wiki/Eval#Uses) is pretty informative, and details various uses.
Some of the uses it suggests are:
* Evaluating mathematical expressions
* [Compiler bootstrapping](http://en.wikipedia.org/wiki/Bootstrapping_(compilers))
* Scripting (dynamic languages in general are very suitable to this)
* Language tutors | Use of eval in Python | [
"",
"python",
"dynamic",
"eval",
""
] |
I'm a long time Unix and Linux person with about 30 years and 14 years experience in those technologies, respectively. But wanting to expand my toolbox, I was trawling SO for hints on learning Sharepoint and I was wondering about Jon Skeet's answer to the question "[How to begin as a .net and SharePoint developer](https://stackoverflow.com/questions/182449/how-to-begin-as-a-net-and-sharepoint-developer)" where he suggests learning .NET and C# before learning ASP.NET and Sharepoint.
Should I learn .NET and C# before getting involved with ASP.NET and Sharepoint? And can anyone recommend good books for the four technologies?
On SO so far, we've had questions for book recommendations for learning Sharepoint and ASP.NET but I haven't found anything about a "\*nix head" dipping his toes into the MS waters for the first time.
At the moment I have Jon's recommendations from his answer above but I've been also been looking at the Head First C# book and a couple of O'Reilly Nutshell books.
The list of possible books I have so far is:
**C#:**
* "Accelerated C# 2008 ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/1590598733))
* "Head First C#" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/0596514824))
* "Learning C# 3.0" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/0596521065))
* "Programming C# 3.0" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/0596527438))
**Sharepoint:**
* "Inside Microsoft Windows SharePoint Services 3.0" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/0735623201))
* "Microsoft SharePoint: Building Office 2007 Solutions in C# 2005" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/1590598091))
* "Workflow in the 2007 Microsoft Office System" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/1590597001))
* "Professional SharePoint 2007 Development" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/0470117567))
* "Real World SharePoint 2007: Indispensable Experiences From 16 MOSS and WSS MVPs" ([sanitised Amazon link](https://rads.stackoverflow.com/amzn/click/com/0470168358))
N.B. The Sharepoint list was obtained from the accepted answer to the question "[WSS/MOSS](https://stackoverflow.com/questions/14546/wss-moss-book)". Thanks Pascal Paradis.
Any one help with the suggestions for learning .NET and ASP.NET?
Any thoughts on these books? | This really deserves something more than "Should you walk before you can run?", which was my first thought :)
With 30 odd years of experience (I assume programming experience), you should not really learn the basics, you need to get in depth understanding of the C# developement environment, IIS, SQL Server and SharePoint (in roughly that order).
To be efficient, you need to compare these technologies and see how they are different from what you are used to rather than reading yet another book that starts with variable declaration syntax.
I personally would get more from time spent with an expert, but that is not usually an option. Fortunately many of these people blog and those can be really illuminating.
(see [Eric Lippert](http://blogs.msdn.com/ericlippert/))
When reading the detail, you will most likely be able to understand how the details operate without needing a full chapter.
Small snippets of information are going to be more useful to you than large amounts of basic knowledge.
E.g. I assume that a snippet of information such as "SharePoint stores all the documents for a Site Collection as a binary field in a [single table](http://msdn.microsoft.com/en-us/library/ms998690.aspx)." will provide you with more information than a several thousand word overview of SharePoint site collections. | As with any language, you will need something to do while learning C#. While you can do sample projects as shown in the books, as an experienced developer, I would personally recommend learning by doing an ASP.NET project (you don't need to write a lot of "this is a function" type exercises as C# functions are pretty much the same as any c-style functions).
In short, I *would* put off Sharepoint development due to its very specific nature, but *not* ASP.NET development.
Update: One other thing...Visual Studio makes web development quite straightforward. It is not as if Windows development is so much simpler than Web Development that it makes it easier to focus on the C#. It is more the case that each environment (Winforms versus Web) provides a different context within which C# is used. Thus, you may as well learn C# within the Web context since that will be your long-term focus.
One other thing: you may want to see [this answer](https://stackoverflow.com/questions/389487/im-new-to-net-what-should-i-concentrate-on-and-what-should-i-ignore/389574#389574) that I offered to an earlier question about getting started with .NET. | Should I learn .NET and C# before learning ASP.NET and Sharepoint? | [
"",
"c#",
".net",
"asp.net",
"sharepoint",
""
] |
My code is :
```
//cron.html
<head>
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 11">
<meta name=Originator content="Microsoft Word 11">
<
</head>
<body>
<form method="post" action="CETrafficGenerator.php?step=2">
<input type="text" name="url"/>
</body>
</html>
```
instead of typing the url can i pass it through cron.html?url=
in this format?
Help needed please | Yes you could do, but you would have to fill it into the form field using javascript. You can use jQuery to make this easier - see <http://projects.allmarkedup.com/jquery_url_parser/> for more info. Example:
```
$('url).value = jQuery.url.param('url');
```
And then make the form field like this:
```
<input type="text" name="url" id="url" value="" />
``` | Short answer == No
You'll need some sort of programming (php, asp, javascript) to take the value of the querystring and insert it to your text box. | passing form parameters through html | [
"",
"javascript",
"html",
"parameters",
""
] |
I am attempting to get Memory leak detection working with the help of these two articles:
<http://msdn.microsoft.com/en-us/library/e5ewb1h3%28VS.80%29.aspx>
<http://support.microsoft.com/kb/q140858/>
So in my stdafx.h I now have:
```
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define new new(_NORMAL_BLOCK,__FILE__,__LINE__)
```
The only problem is, I have a class which overrides the new function:
```
class Dummy
{
//overloaded new operator
void FAR* operator new(size_t cb);
}
```
Now when I compile this code, I get:
error C2059: syntax error : 'constant'
error C2091: function returns function
Any idea how I can fix this? | You can use pragma directives to save and restore the new macro when undefing for overloads. See [MSDN](<http://msdn.microsoft.com/en-us/library/hsttss76(VS.71).aspx)> for the exact syntax.
E.g.
```
#pragma push_macro("new")
#undef new
void FAR* operator new(size_t cb);
#pragma pop_macro("new")
```
You can put these in headers, e.g.
begin\_new\_override.h:
```
#ifdef new
#define NEW_WAS_DEFINED
#pragma push_macro("new")
#undef new
#endif
```
end\_new\_override.h:
```
#ifdef NEW_WAS_DEFINED
#undef NEW_WAS_DEFINED
#pragma pop_macro("new")
#endif
```
And then
```
#include "begin_new_override.h"
void FAR* operator new(size_t cb);
#include "end_new_override.h"
``` | Instead of defining new to be something different, why not overload operator new?
Add these function definitions somewhere in the global namespace:
```
// operator new overloads
void* operator new( const size_t size, const char* file, int line) throw();
void* operator new( const size_t size, const size_t align, const char* file, int line) throw();
void* operator new[]( const size_t size, const char* file, int line) throw();
void* operator new[]( const size_t size, const size_t align, const char* file, int line) throw();
// can't easily overload operator delete
void operator delete( void* ptr ) throw();
void operator delete[]( void* ptr ) throw();
// matched to the operator new overload above in case of exceptions thrown during allocation
void operator delete( void* ptr, const char* file, int line) throw();
void operator delete[]( void* ptr, const char* file, int line) throw();
void operator delete( void* ptr, const size_t align, const char* file, int line) throw();
void operator delete[]( void* ptr, const size_t align, const char* file, int line) throw();
// global new/delete
void* operator new( size_t size ) throw();
void* operator new( size_t size, const std::nothrow_t& ) throw();
void* operator new( size_t size, size_t align ) throw();
void* operator new( size_t size, size_t align, const std::nothrow_t& ) throw();
void* operator new[]( size_t size ) throw();
void* operator new[]( size_t size, const std::nothrow_t& ) throw();
void operator delete( void* ptr, const std::nothrow_t&) throw();
void operator delete[]( void* ptr, const std::nothrow_t&) throw();
```
Then you can define your own new macro which calls through to the non-global versions and implement the global versions to assert or warn if they're called (to catch anything slipping through).
```
#define MY_NEW(s) new(s, __FILE__, __LINE__)
```
Your class-level overloads will work as expected if you call 'new' directly on the class. If you want to call MY\_NEW on the class, you can but you'll have to redefine the overload in the class to match your new. | Memory Leak Detecting and overriding new? | [
"",
"c++",
"memory-leaks",
"unmanaged",
""
] |
I've been trying to get the Zend Jquery autocomplete function working, when i noticed this section in the [Zend documentation](http://framework.zend.com/manual/en/zendx.jquery.view.html).
> The following UI widgets are available as form view helpers. Make sure you use the correct version of jQuery UI library to be able to use them. The Google CDN only offers jQuery UI up to version 1.5.2. **Some other components are only available from jQuery UI SVN, since they have been removed from the announced 1.6 release**.
>
> autoComplete($id, $value, $params, $attribs): The AutoComplete View helper will be included in a future jQuery UI version (currently only via jQuery SVN) and creates a text field and registeres it to have auto complete functionality. The completion data source has to be given as jQuery related parameters 'url' or 'data' as described in the jQuery UI manual.
Does anybody know which svn url tag or branch i need to download to get a javascript file with the autocomplete functions available in it?
At the moment, my Bootstrap.php has
```
$view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');
$view->jQuery()->enable();
$view->jQuery()->uiEnable();
Zend_Controller_Action_HelperBroker::addHelper(
new ZendX_JQuery_Controller_Action_Helper_AutoComplete()
);
// Add it to the ViewRenderer
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
```
In my layout, i define the jquery ui version i want
```
<?php echo $this->jQuery()
->setUiVersion('1.7.2');?>
```
Finally my index.phtml has the autocomplete widget
```
<p><?php $data = array('New York', 'Tokyo', 'Berlin', 'London', 'Sydney', 'Bern', 'Boston', 'Baltimore'); ?>
<?php echo $this->autocomplete("ac1", "", array('data' => $data));?></p>
```
I'm using Zend 1.8.3 atm. | Last time I checked, it was in the [dev branch](http://jquery-ui.googlecode.com/svn/branches/dev/autocomplete/).
The only issue is that I'm not sure how complete and ready this is, **and** if it even works with ZendX\_Jquery. You can stay up to date on [the progress of autoComplete on the official wiki page](http://jqueryui.pbworks.com/Autocomplete). | I exported the code from the link provided by Till above and copied the ui.autocomplete.[js & css] to the public folder of my ZEND app, into a sub folder i called 'js/autocomplete'.
My updated code now looks like
Bootstrap.php : add the extra autocomplete js script to the page
```
$view->jQuery()->addJavascriptFile('/js/autocomplete/ui.autocomplete.js');
```
layout.phtml : add autocomplete css and jquery theme, i also say to use the latest version of jquery
```
<?php echo $this->jQuery()
->setUiVersion('1.7.2')
->addStylesheet('/js/autocomplete/ui.autocomplete.css')
->addStylesheet('/js/jquery-ui-1.7.2/development-bundle/themes/ui-lightness/jquery-ui-1.7.2.custom.css');?>
```
index.phtml : this is a copy paste code sample from the Zend documentation.
```
<h3>AutoComplete</h3>
<p><?php $data = array('New York', 'Tokyo', 'Berlin', 'London', 'Sydney', 'Bern', 'Boston', 'Baltimore'); ?>
<?php echo $this->autocomplete("ac1", "", array('data' => $data));?></p>
```
Works like a charm. :-)
Your final html should have the following structure in the head element.
```
<link rel="stylesheet" href="/js/autocomplete/ui.autocomplete.css" type="text/css" media="screen" />
<link rel="stylesheet" href="/js/jquery-ui-1.7.2/development-bundle/themes/ui-lightness/jquery-ui-1.7.2.custom.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="/js/autocomplete/ui.autocomplete.js"></script>
``` | Zendx JQuery Autocomplete | [
"",
"php",
"jquery",
"zend-framework",
"jquery-ui",
""
] |
C++ does not allow polymorphism for methods based on their return type. However, when overloading an implicit conversion member function this seems possible.
Does anyone know why? I thought operators are handled like methods internally.
Edit: Here's an example:
```
struct func {
operator string() { return "1";}
operator int() { return 2; }
};
int main( ) {
int x = func(); // calls int version
string y = func(); // calls string version
double d = func(); // calls int version
cout << func() << endl; // calls int version
}
``` | Conversion operators are not really considered different overloads and they are not called based on *their return type*. The compiler will only use them when it **has to** (when the type is incompatible and should be converted) or when explicitly asked to use one of them with a cast operator.
Semantically, what your code is doing is to declare several **different** type conversion operators and **not overloads of a single operator**. | That's not return type. That's type conversion.
Consider: func() creates an object of type func. There is no ambiguity as to what method (constructor) will be invoked.
The only question which remains is if it is possible to cast it to the desired types. You provided the compiler with appropriate conversion, so it is happy. | Why do implicit conversion member functions overloading work by return type, while it is not allowed for normal functions? | [
"",
"c++",
"polymorphism",
"implicit-conversion",
""
] |
I have the following script:
```
Timer=0;
function countdown(auctionid){
var auctions;
var divs;
Timer=Timer+1;
if((Timer%10=="0")||(Timer=="1")){
$.get("current.php", {
id:auctionid
},
function(data){
auctions=data.split("||");
for(n=0;n<=auctions.length;n++){
if(auctions[n] != undefined){
divis=auctions[n].split("##");
$('#futu'+divis[0]).html(divis[1]);
}
}
}
);
}
var cauctionid="auctionid";
var tauctions=auctionid.split("|");
for(i=0;i<=tauctions.length;i++){
if(tauctions[i] != undefined){
var dd=$('#futu'+tauctions[i]).text();
var cdd=dd-1;
$('#futu'+tauctions[i]).html(cdd);
dd=dd*1000;
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor(dd/(60*60*1000)*1)
dmin=Math.floor((dd%(60*60*1000))/(60*1000)*1)
dsec=Math.floor(((dd%(60*60*1000))%(60*1000))/1000*1)
if(dday==0&&dhour==0&&dmin==0&&dsec==0){
$('#Bid'+tauctions[i]).html("SOLD");
//return
}
if(dhour <=9){
dhour = "0"+dhour;
}
if(dmin <=9){
dmin = "0"+dmin;
}
if(dsec <=9){
dsec = "0"+dsec;
}
if(dd>=1000){
var valll=dhour+":"+dmin+":"+dsec;
}
if(dd<1000){
var valll="00:00:00";
}
$('#Bid'+tauctions[i]).html(valll);
}
}
refreshID=setTimeout("countdown('"+auctionid+"')",1000);
}
```
On the line that reads:
if((Timer%10=="0")||(Timer=="1")){
How do i make the 10, a random number between 2 and 12? | You want to use the [`random()`](http://www.w3schools.com/jsref/jsref_random.asp) function. There is no version that returns an integer unfortunately, only a float between 0 and 1, so you'll need to do a few operations. Try the following:
```
var randomNum = Math.floor(Math.random() * 10) + 2;
```
This should generate a random integral number between 2 (inclusive) and 12 (exclusive). Change 10 to 11 if you want the 12 to be inclusive, of course. | See the answers to this [question](https://stackoverflow.com/questions/424292/how-to-create-my-own-javascript-random-number-generator-that-i-can-also-set-the-s) which also allows you to set the seed value. | Javascript Random Number? | [
"",
"javascript",
"random",
""
] |
I've built a simple cms with an admin section. I want to create something like a backup system which would take a backup of the information on the website, and also a restore system which would restore backups taken. I'm assuming backups to be SQL files generated of the tables used.
I'm using PHP and MySQL here - any idea how I can do this? | One simple solution for backup:
* Call mysqldump from php <http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html>, and save the backup file somewhere convenient.
* This is a safe solution, because you have mysqldump on any mysql installation, and it's a safe way to generate a standard sql script
* It's also safe to save the whole database.
* Be careful with blobs, like saved images inside database
* Be careful with utf-8 data
One simple solution for restore:
* Restore operation can be done with the saved script.
* First disable access to the the site/app.
* Take down the database.
* Restore the database from the script with mysqlimport <http://dev.mysql.com/doc/refman/5.0/en/mysqlimport.html>
Calling external applications from php:
<http://php.net/manual/en/book.exec.php> | If linux/unix, check out "man pg\_dump". It basically dumps whole databases (with all tables and table definitions), e.g. "pg\_dump mydb > db.sql" | Want to create a script that takes backup of entire database and downloads it | [
"",
"php",
"mysql",
"content-management-system",
"backup",
""
] |
What's an efficient way for someone who knows PHP and Ruby on Rails to quickly pick up the Zend framework? | I think that by already having experience with RoR and PHP, you have already broken the back of the task. RoR follows the same architecture pattern as the Zend Framework (MVC); and so you will already have an abstract understanding of your first Zend Framework application.
I don't know of any resources that are specifically targeted at transitioning RoR programmers to Zend Framework programmers (that would make a good topic for a book), however, with (at least) a syntactic understanding of PHP, I'd recommend you read one of the following introduction articles:
1. [The Official Quick-Start Guide](http://framework.zend.com/docs/quickstart)
2. [Rob Allen's Getting Started with Zend Framework 1.8](http://akrabat.com/zend-framework-tutorial/)
You can always post questions on S.O. if you're stuck! | I'll add the [nabble forum](http://www.nabble.com/Zend-Framework-Community-f16154.html) dedicated to ZF that helped me a lot. | What are good resources for learning the Zend framework? | [
"",
"php",
"zend-framework",
""
] |
> **Possible Duplicate:**
> [Should Usings be inside or outside the namespace](https://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace)
sa1200 All using directives must be placed inside the namespace (StyleCop)
Is this just for code readibility or is there any actual advantage to doing so?
Does it help the GC somehow? | It definitely won't help with GC.
Here's the discussion about two styles:
<https://learn.microsoft.com/en-us/archive/blogs/abhinaba/stylistic-differences-in-using>
<https://learn.microsoft.com/en-us/archive/blogs/abhinaba/do-namespace-using-directives-affect-assembly-loading> | If you have multiple namespaces in your project, you can limit which namespaces are used by each one individually.
This might come in handy if there were class names in two different namespaces that were the same. One might be the default in one part of your project, while the other could be the default in another.
Yes they look for some really fringe cases for these rules. | Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic? | [
"",
"c#",
"stylecop",
""
] |
I would think the following piece of code should work, but it doesn't **(Edited: Now works in PHP 5.5+)**:
```
if (!empty($r->getError()))
```
Where `getError()` is simply:
```
public function getError()
{
return $this->error;
}
```
Yet I end up with this error:
> can't use method return value in write context
What does this mean? Isn't this just a read? | `empty()` needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.
However, the real problem you have is that you use `empty()` at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for `!isset($thing) || !$thing`. When the thing you're checking always exists (in PHP results of function calls always exist), the `empty()` function is *nothing but a negation operator*.
PHP **doesn't have concept of emptyness**. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:
```
$x = something();
if (empty($x)) …
```
and this:
```
$x = something();
if (!$x) …
```
has **always the same result, in all cases, for all datatypes** (because `$x` is defined `empty()` is redundant).
Return value from the method always exists (even if you don't have `return` statement, return value exists and contains `null`). Therefore:
```
if (!empty($r->getError()))
```
is logically equivalent to:
```
if ($r->getError())
``` | > **Note:** This is a very high voted answer with a high visibility, but please note that it promotes bad, unnecessary coding practices! See [@Kornel's answer](https://stackoverflow.com/a/4328049/476) for the correct way.
>
> **Note #2:** I endorse the suggestions to use [@Kornel's answer](https://stackoverflow.com/a/4328049/476). When I wrote this answer three years ago, I merely meant to explain the nature of the error, not necessarily endorse the alternative. The code snippet below is not recommended.
---
It's a limitation of [empty()](https://www.php.net/empty) in PHP versions below 5.5.
> Note: empty() only checks variables as
> anything else will result in a parse
> error. In other words, the following
> will not work: empty(trim($name)).
You'd have to change to this
```
// Not recommended, just illustrates the issue
$err = $r->getError();
if (!empty($err))
``` | Can't use method return value in write context | [
"",
"php",
""
] |
I have some Python code that have inconsistent indentation. There is a lot of mixture of tabs and spaces to make the matter even worse, and even space indentation is not preserved.
The code works as expected, but it's difficult to maintain.
How can I fix the indentation (like [HTML Tidy](https://en.wikipedia.org/wiki/HTML_Tidy), but for Python) without breaking the code?
---
Some **editor-specific** advice:
* Vi/Vim:
+ [Replace tabs with spaces in vim](https://stackoverflow.com/questions/426963)
+ [Expand tabs to spaces in vim only in python files?](https://stackoverflow.com/questions/9986475)
+ [Use Vim Retab to solve TabError: inconsistent use of tabs and spaces in indentation?](https://stackoverflow.com/questions/48735671)
+ [How to maintain tabs when pasting in Vim](https://stackoverflow.com/questions/12584465)
* Notepad++:
+ [Convert tabs to spaces in Notepad++](https://stackoverflow.com/questions/455037)
+ [Auto-indent in Notepad++](https://stackoverflow.com/questions/412427)
+ [How do I configure Notepad++ to use spaces instead of tabs?](https://stackoverflow.com/questions/8197812/)
* Emacs:
+ [Indentation not working properly in emacs for python](https://stackoverflow.com/questions/27032218)
+ [Emacs bulk indent for Python](https://stackoverflow.com/questions/2585091)
* Eclipse:
+ [indent python file (with pydev) in eclipse](https://stackoverflow.com/questions/7654267)
* Visual Studio Code:
+ [Visual Studio Code indentation for Python](https://stackoverflow.com/questions/37143985) | Use the `reindent.py` script that you find in the `Tools/scripts/` directory of your Python installation:
> Change Python (.py) files to use
> 4-space indents and no hard tab
> characters. Also trim excess spaces
> and tabs from ends of lines, and
> remove empty lines at the end of
> files. Also ensure the last line ends
> with a newline.
Have a look at that script for detailed usage instructions.
---
NOTE: If your linux distro does not have reindent installed by default with Python:
Many linux distros do not have `reindent` installed by default with `python` --> one easy way to get `reindent` is to do `pip install reindent`.
p.s. An alternative to `pip` is to use your distros package manager (i.e. `apt-get`, `yum`, `dnf`) but then you need to figure out what package has the command line tool because each distro has the tool in a different package. | I would reach for [autopep8](https://pypi.python.org/pypi/autopep8) to do this:
```
$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff
$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place
```
*Note: [E101 and E121](https://github.com/hhatto/autopep8#features) are pep8 indentation (I think you can simply pass `--select=E1` to fix all indentation related issues - those starting with E1).*
You can apply this to your entire project using recursive flag:
```
$ autopep8 package_dir --recursive --select=E101,E121 --in-place
```
*See also [Tool to convert Python code to be PEP8 compliant](https://stackoverflow.com/a/14328499/1240268).* | How to fix Python indentation | [
"",
"python",
""
] |
We just updated to Mac OSX 10.5.7 and now anytime I bring up any of my SwingUI based dialogs our application crashes. Literally everything was working fine I just made some good progress on the project and decided to take a break and install the update, I come back boot up the application and discover anytime a swingUI based element comes up, the application crashes. Does this seem like a plausible cause of my problem or is it just some crazy coincidence? | Maybe you need a newer version of the quaqua JNI libraries linked against 10.5.7? | Have you tried updating the VM on your Mac? A new update came out recently:
> Java for Mac OS X 10.5 Update 4 delivers improved reliability, security, and compatibility for Java SE 6, J2SE 5.0 and J2SE 1.4.2 on Mac OS X 10.5.7 and later. This release updates Java SE 6 to version 1.6.0\_13, J2SE 5.0 to version 1.5.0\_19, and J2SE 1.4.2 to 1.4.2\_21. | Possible issue with Mac OSX update 10.5.7 and swingUI | [
"",
"java",
"macos",
""
] |
This MySQL script installs multiple triggers.
It works on one machine running MySQL 5.0.51b-community. On another machine running MySQL 14.12 Distrib 5.0.45, for redhat-linux-gnu (i386) it fails, with this error message, which seems to be related to the `DELIMITER // ... // DELIMITER`; syntax :
> **ERROR 1064 (42000) at line 272: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER; DROP TRIGGER IF EXISTS trigger\_name; DELIMITER' at line 1**
The script syntax (summarised) is:
```
DROP TRIGGER IF EXISTS trigger_name;
DELIMITER //
CREATE TRIGGER trigger_name BEFORE UPDATE ON table
FOR EACH ROW BEGIN
-- Trigger logic goes here
END //
DELIMITER;
-- More trigger drop/create statements follow
```
What is wrong with the script, and how can I correct it? | Try
```
DELIMITER ;
```
not
```
DELIMITER;
```
You're actually specifying `;` as an argument to the `DELIMITER` command, so not having the space there may be confusing it. | You need a space between 'DELIMITER' and ';'
```
DELIMITER ;
# not:
DELIMITER;
``` | MySQL DELIMITER syntax errors | [
"",
"sql",
"mysql",
"triggers",
"delimiter",
""
] |
This is a snippet from Google AppEngine tutorial.
```
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
```
I'm not quite sure what **`debug=True`** does inside the constructor call.
Does it create a local variable with name `debug`, assign `True` to it, and pass it to constructor, or is this a way to set a class instance member variable's value in constructor? | Python functions accept keyword arguments. If you define a function like so:
```
def my_func(a, b='abc', c='def'):
print a, b, c
```
You can call it like this:
```
my_func('hello', c='world')
```
And the result will be:
```
hello abc world
```
You can also support dynamic keyword arguments, using special syntax:
```
def my_other_func(a, *b, **c):
print a, b, c
```
* `*b` means that the `b` variable will take all non-named arguments after `a`, as a `tuple` object.
* `**c` means that the `c` variable will take all named arguments, as a `dict` object.
If you call the function like this:
```
my_other_func('hello', 'world', 'what a', state='fine', what='day')
```
You will get:
```
hello ('world', 'what a') {'state': 'fine', 'what': 'day'}
``` | Neither -- rather, `webapp.WSGIApplication` takes an optional argument named `debug`, and this code is passing the value `True` for that parameter.
The reference page for `WSGIApplication` is [here](http://code.google.com/appengine/docs/python/tools/webapp/wsgiapplicationclass.html) and it clearly shows the optional `debug` argument and the fact that it defaults to `False` unless explicitly passed in.
As the page further makes clear, passing `debug` as `True` means that helpful debugging information is shown to the browser if and when an exception occurs while handling the request.
How exactly that effect is obtained (in particular, whether it implies the existence of an attribute on the instance of `WSGIApplication`, or how that hypothetical attribute might be named) is an internal, undocumented implementation detail, which we're not supposed to worry about (of course, you can study the sources of `WSGIApplication` in the SDK if you *do* worry, or just want to learn more about one possible implementation of these specs!-). | Python newbie: What does this code do? | [
"",
"python",
""
] |
Can anyone suggest a book or a tutorial on creating Charts in PHP extracting the data from MySQL Database. It should not involve Flash in any way.
I dont want to use any pre-built charting solutions. | You will probably want to look at using the GD image library.
Here's a tutorial to get you started: [Dynamically Creating Graphs and Charts with PHP and GDChart](http://devzone.zend.com/article/3774). | <http://code.google.com/p/mtchart/>
Open Source PHP charting library (Fork of pChart, more OO-Code), looks way nicer than the current market leader jpGraph.
(Disclamer/Plug-notification: I'm the developer of mtChart.) | References on creating Charts/Graphs in PHP? | [
"",
"php",
"charts",
"graph",
""
] |
Non inline function defined in header file with guards
```
#if !defined(HEADER_RANDOM_H)
#define HEADER_RANDOM_H
void foo()
{
//something
}
#endif
```
Results in linker error : Already defined in someother.obj file
Making the function inline works fine but I am not able to understand why the function is already erroring out in first case. | If the header is included in more than one source file and the function is not marked as "inline" you will have more than one definition. The include guards only prevent multiple inclusions in the same source file. | You're violating [the one definition rule](http://en.wikipedia.org/wiki/One_Definition_Rule). If you want to define a function directly in the header, you must mark it as `inline` -- that will allow the function to be defined multiple times. Also note that `inline` has no other meaning, particularly it doesn't force the compiler to inline calls (contrary to popular belief). | Linker Error on having non Inline Function defined in header file? | [
"",
"c++",
"function",
"header",
"definition",
""
] |
I'm using DataSet to connect my C# program with SQL database. I want one of the columns to be an enumeration and I want it to act as an enum in my code. How can I do this? | I don't mean to burst everyone's bubble, but you can easily map an integer to an Enum using a Strongly Typed DataSet. I do it all the time. Rather than type the whole thing out here I have created an [entry on my Blog](http://www.technofattie.com/2009/06/23/custom-enum-in-strongly-typed-dataset.html) describing in detail how to accomplish this. | I don't think you can. SQL Server doesn't have a concept of enums. | Enum in DataSet | [
"",
"c#",
"enums",
"dataset",
""
] |
I have a simple Python script that uses the socket module to send a UDP packet. The script works fine on my Windows box, but on my Ubuntu Linux PC the packet it sends is slightly different. On Windows the flags field in the IP header is zero, but using the same code on Linux created a packet with the flags field set to 4. I'd like to modify my script so it has consistent behavior on Windows and Linux.
Is there a method for controlling the flags field in the socket module? Or, is this a setting I have to change in Linux? | I'm guessing that the flags field is actually set to 2 = b010 instead of 4 - flags equal to 4 is an invalid IP packet. Remember that flags is a 3 bit value in the [IP Header](http://en.wikipedia.org/wiki/IPv4#Packet_structure). I would expect to see UDP datagrams with a flags value of 2 which means "Don't fragment".
As for your question, I don't believe there is a way to set the IP flags directly without going all of the way to using [raw sockets](http://en.wikipedia.org/wiki/Raw_socket). I wouldn't worry about it since most applications don't really have a good reason to muck with IP or even UDP/TCP headers directly. | Here's the route I ended up taking. I followed the link posted by SashaN in the comments of D.Shwley's answer and learned a little bit about why the "don't fragment" bit is set in Linux's UDP packets. Turns out it has something to do with PMTU discovery. Long story short, you can clear the don't fragment bit from your UDP packets in Python by using the setsockopts function in the socket object.
```
import socket
IP_MTU_DISCOVER = 10
IP_PMTUDISC_DONT = 0 # Never send DF frames.
IP_PMTUDISC_WANT = 1 # Use per route hints.
IP_PMTUDISC_DO = 2 # Always DF.
IP_PMTUDISC_PROBE = 3 # Ignore dst pmtu.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("10.0.0.1", 8000))
s.send("Hello World!") # DF bit is set in this packet
s.setsockopt(socket.SOL_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DONT)
s.send("Hello World!") # DF bit is cleared in this packet
``` | Setting the flags field of the IP header | [
"",
"python",
"sockets",
""
] |
I have a javascript that calls a function each 1 minute. That function sends a bot on the web looking for information to update on my database (quotes, to be exact).
So basically, sometime it's pretty fast and other times the servers dont answer fast... Let's say I have 100 seeks like this to make each 1 minute. They could take anywhere between 10 seconds to 1 minute+ to execute.
**My question is** : If the function is still fetching and/or waiting for data and I call it again (remember I call it each 1 minute), **WILL IT CANCEL THE FIRST CALL to the function**? If not, then will they simply stack and finish before starting the other one or will they run at the same time?
Thanks a bunch! | You may be interested in using Prototype's [Function.PeriodicalExecuter](http://www.prototypejs.org/api/periodicalExecuter) to help you manage functions that take a long time to complete.
If including all of Prototype seems like overkill and you want to implement the functionality by hand, you could either have a boolean-flag that you set when an instance of the function is running; or a counter that is incremented at the head of the function, and decremented before it returns, giving you the total number of instances of that function.
If you are interested in using Prototype, another function that may help you out is [Ajax.PeriodicalUpdater](http://www.prototypejs.org/api/ajax/periodicalUpdater). | Since you are on a single browser thread my guess is it will stack your calls | Javascript : can i automatically call a function many times even if it has not finished being executed? | [
"",
"javascript",
""
] |
What would you recommend for modular development in Java. OSGI is great but it's support for JPA is pitiful. I would really like not to have to write yet another framework, but it seems inevitable. | I don't think the problem is lack of support in OSGI for JPA, but lack of support in JPA implementations for the OSGI classloader. Anyway I digress.
You may have success using OpenJPA with OSGI. The latest versions are already packed as OSGI bundles. I leave also this [link](http://blog.luminis.nl/roller/luminis/entry/jpa_persistence_in_osgi_with) that explains how to get OpenJPA working in Apache Felix. | The best aproach to modular development: **think first, code later, refactor often**. There's no framework / library in the world that can replace thinking. | modular development | [
"",
"java",
"components",
"module",
""
] |
I am writing code in Java where I branch off based on whether a `string` starts with certain characters while looping through a `dataset` and my `dataset` is expected to be large.
I was wondering whether `startsWith` is faster than `indexOf`. I did experiment with 2000 records but not found any difference. | ```
public class Test
{
public static void main(String args[]) {
long value1 = System.currentTimeMillis();
for(long i=0;i<100000000;i++)
{
"abcd".indexOf("a");
}
long value2 = System.currentTimeMillis();
System.out.println(value2-value1);
value1 = System.currentTimeMillis();
for(long i=0;i<100000000;i++)
{
"abcd".startsWith("a");
}
value2 = System.currentTimeMillis();
System.out.println(value2-value1);
}
}
```
Tested it with this piece of code and perf for startsWith seems to be better, for obvious reason that it doesn't have to traverse through string. But in best case scenario both should perform close while in a worst case scenario startsWith will always perform better than indexOf | `startsWith` only needs to check for the presence at the very start of the string - it's doing less work, so it should be faster.
My guess is that your 2000 records finished in a few milliseconds (if that). Whenever you want to benchmark one approach against another, try to do it for enough time that differences in timing will be significant. I find that 10-30 seconds is long enough to show significant improvements, but short enough to make it bearable to run the tests multiple times. (If this were a serious investigation I'd probably try for longer times. Most of my benchmarking is for fun.)
Also make sure you've got varied data - `indexOf` and `startsWith` should have roughly the same running time *in the case where `indexOf` returns 0*. So if all your records match the pattern, you're not really testing correctly. (I don't know whether that was the case in your tests of course - it's just something to watch out for.) | Is "startsWith" faster than "indexOf"? | [
"",
"java",
""
] |
Greetings,
I am trying to perform a copy from one vector (vec1) to another vector (vec2) using the following 2 abbreviated lines of code (full test app follows):
```
vec2.reserve( vec1.size() );
copy(vec1.begin(), vec1.end(), vec2.begin());
```
While the call to vec2 sets the capacity of vector vec2, the copying of data to vec2 seems to not fill in the values from vec1 to vec2.
Replacing the copy() function with calls to push\_back() works as expected.
What am I missing here?
Thanks for your help. vectest.cpp test program followed by resulting output follows.
Compiler: gcc 3.4.4 on cygwin.
## Nat
```
/**
* vectest.cpp
*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec1;
vector<int> vec2;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
vec1.push_back(4);
vec1.push_back(5);
vec1.push_back(6);
vec1.push_back(7);
vec2.reserve( vec1.size() );
copy(vec1.begin(), vec1.end(), vec2.begin());
cout << "vec1.size() = " << vec1.size() << endl;
cout << "vec1.capacity() = " << vec1.capacity() << endl;
cout << "vec1: ";
for( vector<int>::const_iterator iter = vec1.begin(); iter < vec1.end(); ++iter ) {
cout << *iter << " ";
}
cout << endl;
cout << "vec2.size() = " << vec2.size() << endl;
cout << "vec2.capacity() = " << vec2.capacity() << endl;
cout << "vec2: ";
for( vector<int>::const_iterator iter = vec2.begin(); iter < vec2.end(); ++iter ) {
cout << *iter << endl;
}
cout << endl;
}
```
---
output:
```
vec1.size() = 7
vec1.capacity() = 8
vec1: 1 2 3 4 5 6 7
vec2.size() = 0
vec2.capacity() = 7
vec2:
``` | As noted in other answers and comments, you should just use vector's built-in functionality for this. But:
When you `reserve()` elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up `push_back()` because the memory is already allocated.
When you `resize()` the vector, it will allocate enough space for those elements, ***but also add them to the vector***.
So if you resize a vector to 100, you can access elements 0 - 99, but if you reserve 100 elements, they are not inserted yet, just ready to be used.
What you want is something like this:
```
vec2.reserve( vec1.size() );
copy(vec1.begin(), vec1.end(), std::back_inserter(vec2));
```
[`std::back_inserter`](http://www.cplusplus.com/reference/std/iterator/back_inserter/) is defined in [`<iterator>`](http://www.cplusplus.com/reference/std/iterator/) | If the vectors are of the same type, use copy construction or copy assignment:
```
vec2(vec1);
vec2 = vec1;
```
If the vectors aren't the exact same (maybe a different allocator or something, or vec1 is a deque), what you really want is the range-based constructor or range-based assign:
```
vec2(vec1.begin(), vec1.end()); // range-based constructor
vec2.assign(vec1.begin(), vec1.end()); // range-based assignment
```
If you insist on doing it with `std::copy`, the proper method is:
```
copy(vec1.begin(), vec1.end(), back_inserter(vec2));
```
Since reserving the space does not make it assignable. `copy` works by assigning each element to its new value. So `vec2.size()` needs to be at least as large as `vec1.size()` in your case. Calling `reserve` doesn't actually change a vector's size, just its capacity.
In the book *Effective STL*, Scott Meyers argues that nearly all uses of std::copy for insertion should be replaced with range-based member functions. I suggest you pick up a copy, it's a great reference! | STL vector reserve() and copy() | [
"",
"c++",
"stl",
"vector",
"stl-algorithm",
""
] |
I have seen code like this (actually seeing another person type it up):
```
catch (Exception ex)
{
string exception = ex.ToString();
}
```
Is this code bad? If so, why? There is an appropriate "chain of catch handlers (eg more specific one above, filtering down to general catch all Exception, but in the string conversion of the Exception, I guess you are converting a lot more than is probably needed, to a string (All you really need is the InnerMessage or one of the other string properties depending on the scenario). Any thing else wrong with this code?
I have also seen devs put breakpoints on every line of code. What is the point of this? Why not just put one at the top and then use "run to cursor" (love that feature)?
Finally, what's the advantage of using break on all exceptions in Visual Studio? | This developer might not know that you can catch all (managed) exceptions like this ...
```
try
{
// do something
}
catch( Exception )
{
}
```
And not suffer the compiler warning of a catch block like this ...
```
catch( Exception ex )
{
// don't use ex
}
```
Also, he might not know about the [$exception pseudo-register](http://blogs.msdn.com/saraford/archive/2008/09/22/did-you-know-you-can-add-exception-to-the-watch-window-to-see-the-caught-exception-318.aspx). | ```
string exception = ex.ToString();
```
That doesn't DO anything. Better to log it or use MessageBox.Show(...);.
Breakpoints on each line ... not much point - use run to cursor or step over/step in.
Break on all exceptions: I've actually used. I've had exceptions fail quietly that were "handled" by some library silently. Break on all helped me track that down. Additionally "Break on all" can help you make sure you're only getting exceptions you expect (Also helped by not catching a generic "Exception" class but only catching the particular exception. | Strange exception handling practice | [
"",
"c#",
"visual-studio-2008",
"exception",
""
] |
I have some LINQ code that generates a list of strings, like this:
```
var data = from a in someOtherList
orderby a
select FunctionThatReturnsString(a);
```
How do I convert that list of strings into one big concatenated string? Let's say that data has these entries:
```
"Some "
"resulting "
"data here."
```
I should end up with one string that looks like this:
```
"Some resulting data here."
```
How can I do this quickly? I thought about this:
```
StringBuilder sb = new StringBuilder();
data.ToList().ForEach(s => sb.Append(s));
string result = sb.ToString();
```
But that just doesn't seem right. If it is the right solution, how would I go about turning this into an extension method? | How about:
```
public static string Concat(this IEnumerable<string> source) {
StringBuilder sb = new StringBuilder();
foreach(string s in source) {
sb.Append(s);
}
return sb.ToString();
}
```
and:
```
string s = data.Concat();
```
This then has no need for the extra `ToList()` / `ToArray()` step. | Have you tried String.Join? If you're already willing to take the overhead of a .ToList call then instead use .ToArray() and combine it with a call to String.Join.
```
var joined = String.Concat(someQuery.ToArray());
```
Note: My solution is likely not the fastest as it involves a bit of overhead in the array. My suspicion is that it would be faster to go more Marc's route. But in most cases if you're just looking for the quick and dirty way to do it in code, my route will work. | Fastest way to convert a list of strings into a single concatenated string? | [
"",
"c#",
"string",
"extension-methods",
"linq-to-objects",
""
] |
A quick expression anyone please? | ```
var now = DateTime.Now;
var firstDayCurrentMonth = new DateTime(now.Year, now.Month, 1);
var lastDayLastMonth = firstDayCurrentMonth.AddDays(-1);
``` | ```
DateTime now = DateTime.Now;
DateTime lastDayOfLastMonth = now.Date.AddDays(-now.Day);
``` | C#.Net Getting Last day of the Previous Month from current date | [
"",
"c#",
".net",
""
] |
Is it possible to use a library compiled by visual studio in an application compiled by g++ (mingw) on Windows? | * If the library is written in C++ and exposes a C++ interface: no (because the name-mangling differs between g++ and VC++).
* If the library is a static library written in C (or with an `extern "C"` interface): [yes, but certain caveats apply](http://oldwiki.mingw.org/index.php/MixingCompilers?redirectfrom=MixObjects).
* If the library is a DLL with a C interface: [yes, but you'll have to create your own import library](http://www.emmestech.com/moron_guides/moron1.html). | Also see the discussion for question [QT/mingw32 undefined reference errors… unable to link a .lib](https://stackoverflow.com/questions/1137323/qt-mingw32-undefined-reference-errors-unable-to-link-a-lib) | Use libraries compiled with visual studio in an application compiled by g++ (mingw) | [
"",
"c++",
"visual-c++",
"compiler-construction",
"g++",
"linker",
""
] |
I'm a beginner in programming. I've just made a program called "Guessing Game". And it seems to work fine. Can I integrate it into a website? The CMS that I'm using is Mambo.
===
additional info's
Thanks for all your suggestions.
I still don't have any background about Silverlight, WPF and Java Script which I think sounds good. I'm using Windows and I programmed my "Guessing Game" from Microsoft Visual Studio 2008 and it's using Window application forms.
Yes I guess, for the moment I let it be and start to learn Silverlight or Java Script so that I can integrate it on my website:-)
Thanks for all your input guys:-)
Cheers | A standalone executable cannot be directly integrated into a website. You have a few choices though:
* Allow your users to download the executable and run it locally for themselves
* Rewrite your program in JavaScript to have it run directly inside of an HTML page, though this could obviously involve a fair amount of reworking
* Use Microsoft's [Silverlight](http://silverlight.net/) technology, which allows you to code in C# and produce a web-based frontend similar to Adobe Flash. Your program logic should remain the same and you should only have to change the UI code. In fact if you're already using [WPF](http://en.wikipedia.org/wiki/Windows_Presentation_Foundation) for the front end, the transition will be even easier. | There are several questions that you still need to answer.
1. What is your server running? If its not Windows, your exe will not run at all unless it is compatible with Mono or a similar framework for your server's operating system.
2. How does your "Guessing game" interact with the user? If it is through a WinForms GUI, it will you will not be able to use that GUI on the web. If your game is a WPF application your easiest route may be to port it to Silverlight and serve it up on a web page.
It is typically not trivial to make a regular windows application run in a web environment since on on the web you are really running in the browser, not on Windows. | Can an exe compiled from C# be integrated into a website? | [
"",
"c#",
"web",
""
] |
I'm using a compination of actionscript's getPixel and php's imagecreatetruecolor and imagesetpixel to generate a png image of an swf movie inside a browser.
At the moment it will output a 72 dpi image at the same resolution as the swf movie, but I've been asked about the possibility of generating a 300 dpi image instead.
Is this possible? | Flash doesn't really know anything about resolution or dpi. The only way to output an image from flash with the correct amount of pixels and at print quality is to scale your movie to that amount of pixels and use print quality images or vector graphics. Otherwise you're just going to have a programatically scaled image which is no better than just sending the 72dpi image off to print. Long story short, flash is not a good print design platform. | I assume you use `BitmapData.draw` to generate the image? If you scale the swf up (`scaleX` and `scaleY`) before dumping the image to a `BitmapData`, you can get a higher sample rate = a higher DPI.
If you don't want more data, just interpolation (like McWafflestix suggests), you can try using a scale `Matrix` as the second parameter to `draw`. | Can I dynamically generate a 300 dpi image from a flash file? | [
"",
"php",
"flash",
"actionscript",
"image-processing",
"dpi",
""
] |
I am returned the following:
```
<links>
<image_link>http://img357.imageshack.us/img357/9606/48444016.jpg</image_link>
<thumb_link>http://img357.imageshack.us/img357/9606/48444016.th.jpg</thumb_link>
<ad_link>http://img357.imageshack.us/my.php?image=48444016.jpg</ad_link>
<thumb_exists>yes</thumb_exists>
<total_raters>0</total_raters>
<ave_rating>0.0</ave_rating>
<image_location>img357/9606/48444016.jpg</image_location>
<thumb_location>img357/9606/48444016.th.jpg</thumb_location>
<server>img357</server>
<image_name>48444016.jpg</image_name>
<done_page>http://img357.imageshack.us/content.php?page=done&l=img357/9606/48444016.jpg</done_page>
<resolution>800x600</resolution>
<filesize>38477</filesize>
<image_class>r</image_class>
</links>
```
I wish to extract the image\_link in PHP as simply and as easily as possible. How can I do this?
Assume, I can not make use of any extra libs/plugins for PHP. :)
Thanks all | At Josh's answer, the problem was not escaping the "/" character. So the code Josh submitted would become:
```
$text = 'string_input';
preg_match('/<image_link>([^<]+)<\/image_link>/gi', $text, $regs);
$result = $regs[0];
```
Taking usoban's answer, an example would be:
```
<?php
// Load the file into $content
$xml = new SimpleXMLElement($content) or die('Error creating a SimpleXML instance');
$imagelink = (string) $xml->image_link; // This is the image link
?>
```
I recommend using SimpleXML because it's very easy and, as usoban said, it's builtin, that means that it doesn't need external libraries in any way. | You can use SimpleXML as it is built in PHP. | Extract node from XML like data without extra PHP libs | [
"",
"php",
"xml",
""
] |
I have an event handler that needs to determine a type and execute code if it matches a specific type. Originally we cast it to an object and if it wasn't null we executed the code, to speed it up I used reflection and it actually slowed it down and I don't understand why.
here is a code sample
```
Trace.Write("Starting using Reflection");
if (e.Item.GetType() == typeof(GridDataItem))
{
bool isWatch = Convert.ToBoolean(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsWatch"]);
if (isWatch)
{
e.Item.Style["Font-Weight"] = "bold";
}
}
Trace.Write("Ending using Reflection");
Trace.Write("Starting using Cast");
GridDataItem gridItem = e.Item as GridDataItem;
if (gridItem !=null)
{
bool isWatch = Convert.ToBoolean(gridItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsWatch"]);
if (isWatch)
{
gridItem.Style["Font-Weight"] = "bold";
}
}
Trace.Write("Ending using Cast");
```
And this is the trace output I get
```
Starting using Reflection 0.79137944962406 0.576538
Ending using Reflection 0.791600842105263 0.000221
Starting using Cast 0.791623353383459 0.000023
Ending using Cast 0.791649308270677 0.000026
Starting using Reflection 0.876253801503759 0.084604
Ending using Reflection 0.87631790075188 0.000064
Starting using Cast 0.87633445112782 0.000017
Ending using Cast 0.87634950075188 0.000015
```
it's not a lot, but if we had to do this a lot over time it could add up. | Reflection is slow because you are querying the assembly's metadata whereas casting simply changes the type of the object you are referencing.
The assembly's metadata is a useful store of information but that information is best used at *compilation time* rather than at execution time. That metadata is used by the compiler for static type checking (among other things). You are using that same metadata to look up type information at execution time (which is fine if you have no other choice) which is significantly slower than casting. | Reflection has to go at runtime and determine what properties etc. the object has at runtime. Casting tells the application that it should expect that an object has X properties and should function in a certain way. | Why is casting faster than reflection in .NET? | [
"",
"c#",
".net",
"reflection",
"casting",
""
] |
I am new to Team Foundation Server and I'm trying to connect to a project programmatically using c#. I have the following block of code ...
```
string serverName = "http://tfs01:8080";
TeamFoundationServer tfs = new TeamFoundationServer(serverName);
VersionControlServer version = (VersionControlServer)tfs.GetService(typeof (VersionControlServer));
Workspace workspace = version.GetWorkspace("Test", version.AuthenticatedUser);
MessageBox.Show(workspace.Name);
```
When I execute the code I receive the following error ...
```
TF14061: The workspace Test;vercuskis does not exist.
```
The "Test" project is off of the root and is visibile from VS 2008 Team Explorer, I do have security access to it and I use it to check in and out code just fine
I'm not sure if I have the "Test" project referenced correctly within my code. I'm looking for an example of how to reference a project name off of the TFS root.
Thank you, | The problem is that "Test" in your code above refers to the TFS workspace, not the project in TFS. TFS uses an idea called workspaces that you map directories and projects to.
The workspace you are using is shown in the source control explorer windwo towards the top. It says: 'Workspace: ' and then the name of the workspace you are using.
Here is a good resource regarding workspaces: <http://www.woodwardweb.com/teamprise/000333.html>
You will then need to probably get some folder mappings from TFS as well. The TFS documentaiton is sparse, and much of the work I have done with it requires some trial and error to understand how TFS works, and how the API is different from using the source control explorer in visual studio. | Like Brian said, you're confused about what a workspace is. His link is a good one: <http://www.woodwardweb.com/teamprise/000333.html>
If you just want to query history information about the version control system and not checkin/checkout any files, you don't need a workspace at all. Just use the VersionControlServer object.
* QueryItems = "tf dir"
* QueryItemsExtended = "tf properties"
* QueryPendingChanges = "tf status"
* QueryHistory = "tf history" -- beware, enumeration causes additional server roundtrips via **yield return**
* etc etc | Connecting to a Team Foundation Server workspace using GetWorkspace | [
"",
"c#",
"version-control",
"tfs",
"workspace",
""
] |
I have a long running console app running through millions of iterations. I want to **benchmark if memory usage increases linerally as the number of iterations increases**.
What would be the best way to go about this?
I think I really only need to be concerned with **Peak memory usage** during a run right? I basically need to work out what is the max number of iterations I can run on this hardware given the memory on the Server.
I am going to setup a batch lot of runs and Log the results over different interation sizes and then graph the results to **identify a memory usage trend** which can then be extrapolated for any given hardware.
Looking for advice on the best way to implement this, **what .net methods, classes to use** or should I use external tools. This article <http://www.itwriting.com/dotnetmem.php> suggests I should profile my own app via code to **factor out shared memory used by the .net runtime** across other apps on the box.
Thanks | There are several ways to do this:
### Perfmon UI
You can use the Performance Montior control panel applet (in Administrative Tools) that comes with Windows to monitor your application. Have a look at the .Net CLR Memory category and the counters inside it. You can also limit the monitoring to just your process. This is probably the easiest as it requires no code changes.
### Perfmon API
You can programmatically use performance counters from .Net. For this, you'll need to use the [PerformanceCounter](http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx) class. This is just an API to the same underlying information that the above UI presents.
### Memory Profiler
You can use a memory profiler to profile you application whilst it is running. The two I have used with success are the [ANTS Memory Profiler](http://www.red-gate.com/products/ants_memory_profiler/index.htm) from RedGate and the [.Net Memory Profiler](http://www.memprofiler.com/) from SciTech. Again, this requires no code changes, but may cost you money (although there are free trial versions). There is also the [CLR Profiler](http://www.microsoft.com/downloads/details.aspx?familyid=86ce6052-d7f4-4aeb-9b7a-94635beebdda&displaylang=en) (a howto can be found [here](http://msdn.microsoft.com/en-us/library/ms979205.aspx)).
### Roll Your Own
You can get hold of some limited memory information from the [Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) class. Get hold of the current process using [Process.GetCurrentProcess()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx), and then look at the properties of it, specifically the ones relating to memory ([MinWorkingSet](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.minworkingset.aspx), [MaxWorkingSet](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.maxworkingset.aspx), [PagedMemorySize64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.pagedmemorysize64.aspx), [PeakPagedMemorySize64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.peakpagedmemorysize64.aspx), [PeakVirtualMemorySize64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.peakvirtualmemorysize64.aspx), [PeakWorkingSet64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.peakworkingset64.aspx), [PrivateMemorySize64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.privatememorysize64.aspx), [VirtualMemorySize64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.virtualmemorysize64.aspx), [WorkingSet64](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.workingset64.aspx)). This is probably the worst solution as you have to do everything yourself, including data collection and reporting.
---
If all you are wanting to do is to verify your application doesn't linearly increase its memory usage as your the number of iterations increases, I would recommend monitoring using the Performance Monitor UI in Windows. It will show you what you need with minimal effort on your part. | [Windows perfmon](http://technet.microsoft.com/en-us/magazine/2008.08.pulse.aspx?pr=blog) is great for this kind of stuff. You have counters for all the managed heaps and for private bytes, if you need to cross correlate with iteration counts you can [publish your own](http://msdn.microsoft.com/en-us/library/ms979204.aspx) perfmon counters from .Net. | c# windows app - profiling peak memory usage and identifying trends | [
"",
"c#",
"memory",
"profiling",
""
] |
I have a table with three fields, FirstName, LastName and Email.
Here's some dummy data:
```
FirstName | LastName | Email
Adam West adam@west.com
Joe Schmoe NULL
```
Now, if I do:
```
SELECT CONCAT(FirstName, LastName, Email) as Vitals FROM MEMBERS
```
Vitals for Joe is null, as there is a single null field. How do you overcome this behaviour? Also, is this the default behaviour in MS SQL Server? | Try
```
ISNULL(FirstName, '<BlankValue>') -- In SQL Server
IFNULL(Firstname, '<BlankValue>') -- In MySQL
```
So,
```
CONCAT(ISNULL(FirstName,''),ISNULL(LastName,''),ISNULL(Email,'')) -- In SQL Server
CONCAT(IFNULL(FirstName,''),IFNULL(LastName,''),IFNULL(Email,'')) -- In MySQL
```
would return the same thing without the null issue (and a blank string where nulls should be). | Look at `CONCAT_WS`
For example:
```
CONCAT_WS('',NULL,"TEST STRING","TEST STRING 2")
```
Yields
`TEST STRINGTEST STRING 2`
This is easier than constructing `IFNULL` around everything. You can use an empty string as the separator. | CONCAT'ing NULL fields | [
"",
"sql",
"sql-server",
"concatenation",
""
] |
**My code:**
```
year=[51-52,53,55,56,58,59,60,61]
photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}]
for i in range(7):
print "<img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\">"
```
I run it and I get
```
File "/tmp/aku.py", line 2
photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}]
^
SyntaxError: invalid syntax
```
I want the following output
```
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG">
...
```
I also run the same code with the syntax for list unsuccessfully
photo={[70,72,73],...}
**How can you make the Python code to work?** | So here is your simple solution to your simple problem
```
year=['51-52', '53', '55' , '56' , '58', '59', '60', '61']
photo=[[70,72,73], [64,65,68],[79,80,81,82],[74,77,78],[60,61,62],[84,85,87],[57,58,59],[53,54,55,56]]
for i in range(len(year)):
for j in range(len(photo[i])):
print '<img src=\"http://files.getdropbox.com/u/100000/Akuja/%s/P10104%s.JPG>' % (year[i], photo[i][j])
``` | Braces are used to indicate a dictionary (associative array). You want to use square brackets, which indicates a list.
Also you probably don't want 51-52 in that first line, as that will evaluate to -1. You should put "51-52" to ensure that it is a string.
Then to get the indexing that you seem to want, you need to do year\*\*[i]\*\* instead of just year, which prints out the whole list. | Unable to put a variable in Python's print | [
"",
"python",
""
] |
How critical are transaction logs after a full backup of a SQL2005 database?
Example: I have a database called **Test** and I don't care about point in time recovery using transaction logs except that I might want to revert back to the database version taken at the time of the last FULL backup.
Now, in the backups directory I have a FULL backup called Test.bak plus 4 associated .trn files. If I make another new backup called Test1.bak is it safe for me to delete the Test.bak + the .trn files from the previous backup sequence? If I delete all backup files except for my Test1.bak, will I be able to recover from that one file only OR should I expect recovery problems because the .trn files are gone? | You can ignore the transaction log files for all intents and purposes, if you don't want to use them for log shipping or as part of your backup strategy.
Transaction log files serve two purposes, and by far the most important is to maintain data integrity in the event of a crash (and for short term transaction management). The second purpose involves backup, as is inferred by the question, and that purpose also facilitates log shipping and related things.
If you're not using transaction logs in a given database for anything other than its usual crash recovery/integrity behaviour, you might as well engage the Simple recovery mode, which in turn enables the "`trunc. log on checkpoint`" database option. When this happens, the transaction log *can't* be backed up, and it's truncated periodically. Instant hassle-free transaction logs! | You don't need transaction log backups at all if you're not interested in point in time recovery. You can always recover the database from the full database backup.
However, I cannot think of a good reason not to be interested in point-in-time recovery unless it is a dev or a test database (like yours). | How critical are transaction logs after a full backup of a SQL2005 database? | [
"",
"sql",
"sql-server-2005",
"backup",
""
] |
Bit of a strange question here i know.
but i wanted to know if some kind of standalone engine for javascript exists..
basically i want to test running of my javascript without having to load a web page...
Maybe it doesn't exist? Like some kind of ide where i can run commands directly without launching IE etc...
I have a great editor but it doesn't support that.. i still need to launch ie / firefxo
What i was thinking of some kind of standalone javascript engine existed that i could write my code here and make debugging a bit easier... and then copy to my webpage.
I know firebug exists but you can't specifically do what i am asking cna you?
Any ideas? | Check out [Rhino](http://mozilla.github.io/rhino/) or [Spidermonkey](https://spidermonkey.dev/). You might want to grab an implementation of the [ServerJS standard](https://wiki.mozilla.org/ServerJS), like [Narwhal](http://narwhaljs.org/) while you're at it. | As for the engine - it's actually built in Windows itself and IE just uses it for webpages. Try it - you can make a simple `.js` file and run it. It's a great replacement for `.bat` files actually. :) You can also `cscript.exe` (for console) and `wscript.exe` (for windows app) to run your scripts. It's actually what Windows internally runs when you double-click a `.js` file.
As for debugging - I don't know. I know that:
* Visual Studio supports script debugging, at least for browsers (but probably in other apps to that integrate with the Windows Scripting Host);
* There is a separate "Script Debugger" downloadable for free from Microsoft, though last I checked it was pretty crappy;
* The above mentioned `cscript.exe` and `wscipt.exe` have command-line parameters that have something to do with script debugging, although I don't know what they do. | Running javascript standalone engine? | [
"",
"javascript",
"ide",
""
] |
By alphabetically by length I mean as follows:
given:
{ "=", "==>>", "=>>", "=>", "!>" }
I want to get out:
```
!>
=
=>
=>>
==>>
```
I'm currently just using OrderBy(x => x.Length).ToArray()
anyone got a better lambda?
Is this reasonably possible? lol, I'm not sure what the rule conventions here would be :-( | Writing your own string comparer you can do this, which meets both set of requirements you've posted.
```
public class MyStringComparer : IComparer<string>
{
#region IComparer<string> Members
public int Compare(string x, string y)
{
if (x[0] == y[0])
{
return x.Length.CompareTo(y.Length);
}
else return x[0].CompareTo(y[0]);
}
#endregion
}
```
a bcde bcd b bced cb
would yield:
a b bcd bcde bced cb
and { "=", "==>>", "=>>", "=>", "!>" }
yields:
```
!>
=
=>
=>>
==>>
```
by calling: `myStringCollection.OrderBy(x=>x, new MyStringComparer).ToArray();` | If you want to sort by Alpha then by length, use the OrderBy and ThenBy methods:
```
var strings = new List<string> { "=", "==>>", "=>>", "=>", "!>" };
strings = strings.OrderBy( x => x ).ThenBy( x => x.Length ).ToList();
strings.ForEach( Console.WriteLine );
``` | How do I sort a string array alphabetically by length? | [
"",
"c#",
".net",
"sorting",
"lambda",
""
] |
Is there any equivalent function that returns the character at position `X` in PHP?
I went through the documentation but couldn't find any. I am looking for something like:
```
$charAtPosition20 = strCharAt(20, $myString);
``` | For single-byte strings you can use: `$myString[20]` (note that indices start from 0).
For multi-byte strings see the [answer below](https://stackoverflow.com/questions/1128599/is-there-any-equivalent-function-that-returns-the-character-at-position-x-in-p#64367233) | There are two ways you can achieve this:
1. Use square brackets and an index to directly access the character at the specified location, like: `$string[$index]` or `$string[1]`;
2. Use the `substr` function: `string substr ( string $string , int $start [, int $length ] )`
See <https://www.php.net/manual/en/function.substr.php> for further informations. | Is there any equivalent function that returns the character at position `X` in PHP? | [
"",
"php",
"string",
""
] |
I have a form being inserted into a page with jQuery. In all other browsers, it submits correctly... but in Chrome, some extra form fields from other forms on the page are being added to the POST. I'm not using javascript to submit the form, the form is just added with javascript and then submitted with a standard submit input.
Has anyone else had similar experience? Or any ideas on how to deal with this?
Thanks | The issue is with the insertion of a `noscript` tag into the DOM via javascript. I was receiving some HTML from the server with a `noscript` tag that had a `select` tag in that. Apparently WebKit-based browsers submit that input with the form.
The simple fix was to parse the HTML with jQuery and remove the noscript tags like so:
```
$response.find('noscript').remove();
``` | If the form is nested within another form, this could trigger the browser in being unable to work out which form and its values you want to send and will try and do its best to send whatever values it thinks belongs to the form. | Why is Chrome submitting extra form fields? Is it a bug with Chrome? | [
"",
"javascript",
"jquery",
"forms",
"google-chrome",
""
] |
I'm building an application with C# code.
How do I get only the date value from a `DateTimePicker` control? | I'm assuming you mean a datetime picker in a winforms application.
in your code, you can do the following:
```
string theDate = dateTimePicker1.Value.ToShortDateString();
```
or, if you'd like to specify the format of the date:
```
string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
``` | ```
DateTime dt = this.dateTimePicker1.Value.Date;
``` | How to get only the date value from a Windows Forms DateTimePicker control? | [
"",
"c#",
"winforms",
"date",
"datetimepicker",
""
] |
I'm using OleDb to select data from excel spreadsheets. Each spreadsheet can contain many small tables, and possibly furniture like titles and labels. So it might look like this, where we have two tables and some titles;
```
A B C D
1 . . . .
2 . . . .
3 Table1 . . .
4 Header1 HEADER2 . .
5 h huey . .
6 d dewey . .
7 l loius . .
8 s scrooge . .
9 . . . .
10 . . . .
11 . . . .
12 . . . .
13 . Table 2 . .
14 . HEADER1 HEADER2 HEADER3
15 . 1 foo x
16 . 2 bar y
17 . 3 baz z
18 . . . .
19 . . . .
```
In a previous step, the user has selected the headers of the table they are interested in; in this case, looking at table 2 they will have selected the range `B14:D14`.
These settings are saved, and then I need to query that table. It may happen over and over, as the spreadsheet data is updated; more rows may be added at any time, but the headers are always fixed. There is a sentinel (blank row) marking the end of data
To select the data in the table, I'm writing a query like this;
```
SELECT * FROM [Sheet1$B14:D65535]
```
to select the data in table 2, and then manually checking for the sentinel row, but this seems unsatisfying. Excel 2003 can only read 65,535 rows (uint16), but excel 2007 can read many more (uint32), so I have to write code which gives a different query for Excel 2003 and 2007 based on the extension of the file (.xls vs .xls?).
Does anyone know of a way to write a query that says either;
* 'select everything down and right of B14'?
* 'select everything in columns B->D'
* 'select B12:D\*' where \* means 'everything you can' | Pre-requisite: you can easily determine in your code what the maximum number number of rows is.
Assuming (1) there's a big overhead per SELECT, so SELECTing a row at a time is slow (2) SELECTing 64K or 8M rows (even if blank) is slow ... so you want to see if somewhere in the middle can be faster. Try this:
Select CHUNKSIZE (e.g. 100 or 1000) rows at a time (less when you would otherwise over-run MAX\_ROWS). Scan each chunk for the blank row that marks end-of-data.
**UPDATE: Actually answering the explicit questions:**
*Q: Does anyone know of a way to write a query that says either;*
*Q1: 'select everything down and right of B14'?*
A1: `select * from [Sheet1$B12:]` doesn't work. You would have to do `...B12:IV` in Excel 2003 and whatever it is in Excel 2007. However you don't need that because you know what your rightmost column is; see below.
*Q2: 'select everything in columns B->D'*
A2: `select
* from [Sheet1$B:D]`
*Q3: 'select B12:D`*`' where `*` means 'everything you can'*
A3: select \* from [Sheet1$B12:D]
Tested with Python 2.5 using the following code:
```
import win32com.client
import sys
filename, sheetname, range = sys.argv[1:4]
DSN= """
PROVIDER=Microsoft.Jet.OLEDB.4.0;
DATA SOURCE=%s;
Extended Properties='Excel 8.0;READONLY=true;IMEX=1';
""" % filename
conn = win32com.client.Dispatch("ADODB.Connection")
conn.Open(DSN)
rs = win32com.client.Dispatch("ADODB.Recordset")
sql = (
"SELECT * FROM [Excel 8.0;HDR=NO;IMEX=1;Database=%s;].[%s$%s]"
% (filename, sheetname, range)
)
rs.Open(sql, conn)
nrows = 0
while not rs.EOF:
nrows += 1
nf = rs.Fields.Count
values = [rs.Fields.Item(i).Value for i in xrange(nf)]
print nrows, values
if not any(value is not None for value in values):
print "sentinel found"
break
rs.MoveNext()
rs.Close()
conn.Close()
``` | Couple possible solutions:
1. Put your tables on separate worksheets, then simply query the whole worksheet.
2. Give each table in Excel a name (in Excel 2007, select the table, right-click, and choose Name a range...), then in your query, use this name instead of "Sheet1$B14:D65535".
Hope that helps.
**EDIT**
Here's a third idea:
I'm not sure what you're using to query your database, but if your query engine supports variables (like Sql Server, for example) you could store the result of...
SELECT COUNT(\*) FROM NameOfServer...Sheet1$
...in a variable called @UsedRowCount, that will give you the number of rows actually used in the worksheet. So, @UsedRowCount = LastRowUsed - InitialBlankRows.
You might then be able to use string concatenation to replace "65535" with @UsedRowCount + @InitialBlankRows. You would have to set @InitialBlankRows to a constant (in your example, it would be 3, since the heading row of the first table is located at Row 4). | OleDb connection to Excel; how do I select fixed width, unbounded height? | [
"",
"c#",
"excel",
"oledb",
""
] |
I'm just trying to get more into stl semantics, and converting old loops over to algorithms where appropriate. I'm having trouble figuring out the best way to transform this loop into a call to copy. Any ideas?
```
vector< vector<float> > rvec;
const float * r[Max] = ...;
// ...
for (int ri=0; ri<N; ri++)
for (int rj=0; rj<M; rj++)
rvec[ri][rj] = r[ri][rj];
``` | ```
rvec.resize(Max);
for (int i = 0; i < Max; ++i) {
rvec[i].resize(M);
std::copy(r[i], r[i] + M, rvec[i].begin());
}
```
If `rvec` itself and each vector in `rvec` already has the correct size, then resizing isn't needed. | Not sure you can do this with only the standard algorithms and no functors (and with those, the code is bound to grow significantly than above).
You know, sometimes a plain loop is just best. STL's algorithms are very nice, but since C++ doesn't have anonymous functions or built in lambdas (yet), taking perfectly readable code such as you show above and converting it to STL algorithms is more of an intellectual exercise than actual improvement, | using copy with multi-dimensional arrays | [
"",
"c++",
"stl",
""
] |
How can you get a single column back from a query instead of a whole object?
I could do something like this to get the whole object, but all I want is the names:
```
IList<Tribble> tribbles = session.CreateCriteria(typeof(Tribble)).List<Tribble>();
IList<string> names = new List<string>();
foreach (Tribble t in tribbles) {
names.Add(t.Name);
}
```
I would like to be able to specify additional criteria, so is it possible to just exclude certain columns from being retrieved? | Here is the solution I eventually ended up using:
```
ICriteria c = session.CreateCriteria(typeof(Tribble));
c.SetProjection(Projections.ProjectionList().Add(Projections.Property("Name")));
IList<string> names = c.List<string>();
```
I got this idea from [this old StackOverflow question](https://stackoverflow.com/questions/695917/nhibernate-only-retrieve-specific-columns-when-using-critera-queries). | Almost five years later..., this is what you could do using NHibernate.Linq:
```
IList<string> names = session.Query<Tribble>().Select(t => t.Name).ToList()
``` | Getting single column from an entity | [
"",
"c#",
"nhibernate",
""
] |
I have mutliple workers SELECTing and UPDATing row.
id status
10 new
11 new
12 old
13 old
Worker selects a 'new' row and updates its status to 'old'.
What if two workers select same row at the same time?
I mean worker1 selects a new row, and before worker one updates its status, worker2 selects the same row?
Should I SELECT and UPDATE in one query or is there another way? | You could LOCK the table before your read, and unlock it after your write. This would eliminate the chance of two workers updating the same record at the same time.
<http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html> | You can use LOCK TABLES but sometimes I prefer the following solution (in pseudo-code):
```
// get 1 new row
$sql = "select * from table where status='new' limit 0, 1";
$row = mysql_query($sql);
// update it to old while making sure no one else has done that
$sql = "update table set status='old' where status='new' and id=row[id]";
mysql_query($sql);
// check
if (mysql_affected_rows() == 1)
// status was changed
else
// failed - someone else did it
``` | MYSQL How can I make sure row does not get UPDATED more than once? | [
"",
"php",
"mysql",
""
] |
I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites.
Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal. | You could use wget
wget -m -k -E [url]
```
-E, --html-extension save HTML documents with `.html' extension.
-m, --mirror shortcut for -N -r -l inf --no-remove-listing.
-k, --convert-links make links in downloaded HTML point to local files.
``` | probably a tool like [wget](http://www.gnu.org/software/wget/) is more appropriate for this type of thing. | Any Python Script to Save Websites Like Firefox? | [
"",
"python",
""
] |
Is there a way to iterate ValueCollection using straight for loop? (not foreach)
e.g.
```
Dictionary<string, List<long>>.ValueCollection somevalues = somecollection.Value.Values;
for(int i = 0; i< somevalues.Count; i++)
{
//now what?
}
``` | No - there's no indexer or anything similar for `ValueCollection`. I suppose you could use:
```
for (int i = 0; i < someValues.Count; i++)
{
var item = someValues.ElementAt(i);
...
}
```
but that would perform like a dog :) (Just iteration would be O(n^2), as it would be like [Schlemiel the Painter](http://www.joelonsoftware.com/articles/fog0000000319.html).)
Why do you want to do this? If you want items with elements, just keep a counter or use the [overload of `Select` that passes in the index as well as the item](http://msdn.microsoft.com/en-us/library/bb534869.aspx). | You don't *have* to use an index in a for loop...
```
for (var en = somevalues.GetEnumerator(); en.MoveNext(); )
{
var item = en.Current;
// do something useful...
}
``` | "for loop" for ValueCollection | [
"",
"c#",
""
] |
Looking through `decimal.py`, it uses `NotImplemented` in many special methods. e.g.
```
class A(object):
def __lt__(self, a):
return NotImplemented
def __add__(self, a):
return NotImplemented
```
The [Python docs say](http://docs.python.org/library/constants.html):
> **NotImplemented**
>
> Special value which can be returned by the “rich comparison”
> special methods (`__eq__()`, `__lt__()`,
> and friends), to indicate that the
> comparison is not implemented with
> respect to the other type.
It doesn't talk about other special methods and neither does it describe the behavior.
It seems to be a magic object which if returned from other special methods raises `TypeError`, and in “rich comparison” special methods does nothing.
e.g.
```
print A() < A()
```
prints `True`, but
```
print A() + 1
```
raises `TypeError`, so I am curious as to what's going on and what is the usage/behavior of NotImplemented. | `NotImplemented` allows you to indicate that a comparison between the two given operands has not been implemented (rather than indicating that the comparison is valid, but yields `False`, for the two operands).
From the [Python Language Reference](https://docs.python.org/2.7/reference/datamodel.html#coercion-rules):
> For objects x and y, first `x.__op__(y)`
> is tried. If this is not implemented
> or returns NotImplemented,
> `y.__rop__(x)` is tried. If this is also
> not implemented or returns
> NotImplemented, a TypeError exception
> is raised. But see the following
> exception:
> Exception to the previous
> item: if the left operand is an
> instance of a built-in type or a
> new-style class, and the right operand
> is an instance of a proper subclass of
> that type or class and overrides the
> base's `__rop__()` method, the right
> operand's `__rop__()` method is tried
> before the left operand's `__op__()`
> method. This is done so that a
> subclass can completely override
> binary operators. Otherwise, the left
> operand's `__op__()` method would always
> accept the right operand: when an
> instance of a given class is expected,
> an instance of a subclass of that
> class is always acceptable. | It actually has the same meaning when returned from `__add__` as from `__lt__`, the difference is Python 2.x is trying other ways of comparing the objects before giving up. Python 3.x does raise a TypeError. In fact, Python can try other things for `__add__` as well, look at `__radd__` and (though I'm fuzzy on it) `__coerce__`.
```
# 2.6
>>> class A(object):
... def __lt__(self, other):
... return NotImplemented
>>> A() < A()
True
# 3.1
>>> class A(object):
... def __lt__(self, other):
... return NotImplemented
>>> A() < A()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: A() < A()
```
See [Ordering Comparisions (3.0 docs)](http://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons) for more info. | Python NotImplemented constant | [
"",
"python",
""
] |
I'm trying to find out weather I can do this or not. I have a class called Template. and I want to extend that classes functionality in another file, but I don't want to change the name.
Do I declare it as
```
class template extends template
{
// code here
function foo()
{
}
}
```
or do I just declare it like this?
```
class template
{
// write function
function foo()
{
}
}
``` | You might want to check out [classkit](http://www.php.net/classkit) | Only if the parent class is in another namespace.
```
use SomeNamespace\Template as BaseTemplate;
class Template extends BaseTemplate
{
//...
}
``` | In PHP can you extend a class to the same name? | [
"",
"php",
"class",
"extends",
""
] |
Are there rules of thumb that help determine which to use in what case? Should I prefer one over the other most times?
Thanks! | Extension methods are useful, but they are harder to discover through the IDE than regular methods, since they are not attached to the original class and there are no clues as to where the code for them might reside. There are some [best practice suggestions](http://blogs.msdn.com/vbteam/archive/2007/03/10/extension-methods-best-practices-extension-methods-part-6.aspx) as to where to put them and how to name them, but these are only guidelines and there is no guarantee that someone will follow them.
Usually you would use extension methods if you are only adding functionality to a well known, well used class or interface such as the .Net base classes, that you don't have access to the code for. Extension methods also have the constraint in that you not only have to have the original assembly, you have to have the assembly with the extension methods in it, which must be understood by consumers of your code.
Using inheritance will allow you to add, remove or override functionality, and ensure that it is always present with the class when you build it. | Extension methods should be used when you want to provide an implementation across a variety of types that should share the same behavior, but would otherwise be disimilar. That's why you see extension methods being used on interfaces a lot, because it's a very powerful tool to ensure that any given implementation of an interface will have the same implementation of a given behavior.
For example, the Skip and Take extension methods. | Extension methods versus inheritance | [
"",
"c#",
".net",
"class",
"inheritance",
"extension-methods",
""
] |
I have a drop-down list inside a user control (ASCX) that I want to validate from the page on which I've placed the ASCX, but when I set the ControlToValidate to the drop-down list the page complains that it can't be found. Thanks for any help/suggestions. | Expose the dropdown list with a public property in your user control:
```
public DropDownList DropDownToValidate
{
get
{
return ddlTest;
}
}
```
Then use the UniqueID of the exposed Dropdown to set the control to validate in the page load of the page on which you dropped the user control:
```
protected void Page_Load(object sender, EventArgs e)
{
RequiredFieldValidator1.ControlToValidate = WebUserControl1.DropDownToValidate.UniqueID;
}
``` | The only way I know to do this is to do this in your user control class:
```
[ValidationProperty("Foo")]
public class MyUserControl : UserControl
{
public string Foo
{
get { return(yourDropDown.SelectedValue); }
}
}
```
And then in the page you place the user control on:
```
<asp:RequiredFieldValidator ControlToValidate="yourUserControlName" runat="server" ErrorMessage="You are required to make a selection" />
```
Not *quite* the same thing, but that's the only workaround that I know. | How do I add an ASP.NET control inside an ASCX to an external RequiredFieldValidator programmatically? | [
"",
"c#",
"asp.net",
"validation",
"user-controls",
"ascx",
""
] |
I have to write huge data in text[csv] file. I used BufferedWriter to write the data and it took around 40 secs to write 174 mb of data. Is this the fastest speed java can offer?
```
bufferedWriter = new BufferedWriter ( new FileWriter ( "fileName.csv" ) );
```
**Note:** These 40 secs include the time of iterating and fetching the records from resultset as well. :) . 174 mb is for 400000 rows in resultset. | You might try removing the BufferedWriter and just using the FileWriter directly. On a modern system there's a good chance you're just writing to the drive's cache memory anyway.
It takes me in the range of 4-5 seconds to write 175MB (4 million strings) -- this is on a dual-core 2.4GHz Dell running Windows XP with an 80GB, 7200-RPM Hitachi disk.
Can you isolate how much of the time is record retrieval and how much is file writing?
```
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class FileWritingPerfTest {
private static final int ITERATIONS = 5;
private static final double MEG = (Math.pow(1024, 2));
private static final int RECORD_COUNT = 4000000;
private static final String RECORD = "Help I am trapped in a fortune cookie factory\n";
private static final int RECSIZE = RECORD.getBytes().length;
public static void main(String[] args) throws Exception {
List<String> records = new ArrayList<String>(RECORD_COUNT);
int size = 0;
for (int i = 0; i < RECORD_COUNT; i++) {
records.add(RECORD);
size += RECSIZE;
}
System.out.println(records.size() + " 'records'");
System.out.println(size / MEG + " MB");
for (int i = 0; i < ITERATIONS; i++) {
System.out.println("\nIteration " + i);
writeRaw(records);
writeBuffered(records, 8192);
writeBuffered(records, (int) MEG);
writeBuffered(records, 4 * (int) MEG);
}
}
private static void writeRaw(List<String> records) throws IOException {
File file = File.createTempFile("foo", ".txt");
try {
FileWriter writer = new FileWriter(file);
System.out.print("Writing raw... ");
write(records, writer);
} finally {
// comment this out if you want to inspect the files afterward
file.delete();
}
}
private static void writeBuffered(List<String> records, int bufSize) throws IOException {
File file = File.createTempFile("foo", ".txt");
try {
FileWriter writer = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(writer, bufSize);
System.out.print("Writing buffered (buffer size: " + bufSize + ")... ");
write(records, bufferedWriter);
} finally {
// comment this out if you want to inspect the files afterward
file.delete();
}
}
private static void write(List<String> records, Writer writer) throws IOException {
long start = System.currentTimeMillis();
for (String record: records) {
writer.write(record);
}
// writer.flush(); // close() should take care of this
writer.close();
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000f + " seconds");
}
}
``` | try memory mapped files (takes 300 m/s to write 174MB in my m/c, core 2 duo, 2.5GB RAM) :
```
byte[] buffer = "Help I am trapped in a fortune cookie factory\n".getBytes();
int number_of_lines = 400000;
FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel();
ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length * number_of_lines);
for (int i = 0; i < number_of_lines; i++)
{
wrBuf.put(buffer);
}
rwChannel.close();
``` | Fastest way to write huge data in text file Java | [
"",
"java",
"file",
"resultset",
""
] |
How does Kohana determine if a request is an AJAX one?
Is there anything different in the referrer string? Do I need to add a GET param, perhaps `?ajax=true` ? | It checks if the request is made by XMLHttpRequest since most browser send a header in this case with this indication: header `HTTP_X_REQUESTED_WITH` would be set to `XMLHttpRequest`. | As of v2.3.4
```
/**
* Tests if the current request is an AJAX request by checking the
* X-Requested-With HTTP request header that most popular JS frameworks
* now set for AJAX calls.
*
* @return boolean
*/
public static function is_ajax()
{
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
}
``` | How does request::is_ajax() work in Kohana? | [
"",
"php",
"ajax",
"kohana",
""
] |
I'm trying to use MODI to OCR a window's program. It works fine for screenshots I grab programmatically using win32 interop like this:
```
public string SaveScreenShotToFile()
{
RECT rc;
GetWindowRect(_hWnd, out rc);
int width = rc.right - rc.left;
int height = rc.bottom - rc.top;
Bitmap bmp = new Bitmap(width, height);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap = gfxBmp.GetHdc();
PrintWindow(_hWnd, hdcBitmap, 0);
gfxBmp.ReleaseHdc(hdcBitmap);
gfxBmp.Dispose();
string fileName = @"c:\temp\screenshots\" + Guid.NewGuid().ToString() + ".bmp";
bmp.Save(fileName);
return fileName;
}
```
This image is then saved to a file and ran through MODI like this:
```
private string GetTextFromImage(string fileName)
{
MODI.Document doc = new MODI.DocumentClass();
doc.Create(fileName);
doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image img = (MODI.Image)doc.Images[0];
MODI.Layout layout = img.Layout;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < layout.Words.Count; i++)
{
MODI.Word word = (MODI.Word)layout.Words[i];
sb.Append(word.Text);
sb.Append(" ");
}
if (sb.Length > 1)
sb.Length--;
return sb.ToString();
}
```
This part works fine, however, I don't want to OCR the entire screenshot, just portions of it. I try cropping the image programmatically like this:
```
private string SaveToCroppedImage(Bitmap original)
{
Bitmap result = original.Clone(new Rectangle(0, 0, 250, 250), original.PixelFormat);
var fileName = "c:\\" + Guid.NewGuid().ToString() + ".bmp";
result.Save(fileName, original.RawFormat);
return fileName;
}
```
and then OCRing this smaller image, however MODI throws an exception; 'OCR running error', the error code is -959967087.
Why can MODI handle the original bitmap but not the smaller version taken from it? | Looks as though the answer is in giving MODI a bigger canvas. I was also trying to take a screenshot of a control and OCR it and ran into the same problem. In the end I took the image of the control, copied the image into a larger bitmap and OCRed the larger bitmap.
Another issue I found was that you must have a proper extension for your image file. In other words, .tmp doesn't cut it.
I kept the work of creating a larger source inside my OCR method, which looks something like this (I deal directly with Image objects):
```
public static string ExtractText(this Image image)
{
var tmpFile = Path.GetTempFileName();
string text;
try
{
var bmp = new Bitmap(Math.Max(image.Width, 1024), Math.Max(image.Height, 768));
var gfxResize = Graphics.FromImage(bmp);
gfxResize.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
bmp.Save(tmpFile + ".bmp", ImageFormat.Bmp);
var doc = new MODI.Document();
doc.Create(tmpFile + ".bmp");
doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
var img = (MODI.Image)doc.Images[0];
var layout = img.Layout;
text = layout.Text;
}
finally
{
File.Delete(tmpFile);
File.Delete(tmpFile + ".bmp");
}
return text;
}
```
I'm not sure exactly what the minimum size is, but it appears as though 1024 x 768 does the trick. | yes the posts in this thread helped me gettin it to work, here what i have to add:
was trying to download images ( small ones ) then ocr...
-when processing images, it seems that theyr size must be power of 2 !
( was able to ocr images: 512x512 , 128x128, 256x64 .. other sizes mostly failed ( like 1103x334 ))
* transparent background also made troubles. I got the best results when creating a new tif with powerof2 boundary, white background, paste the downloaded image into it, save.
* scaling the image did not succeed for me, since OCR is getting wrong results , specially for "german" characters like "ü"
* in the end i also used: doc.OCR(MODI.MiLANGUAGES.miLANG\_ENGLISH, false, false);
* using modi from office 2003
greetings
womd | .NET OCRing an Image | [
"",
"c#",
".net",
"ocr",
"modi",
""
] |
First, let me start off by saying that I know absolutely nothing about JavaScript or client-side scripting. All of the programming I've ever done has been server-side, mostly PHP, with some Java thrown in too for good measure.
So, I have absolutely no clue where to start with this problem. I have an application with very strict password rules. Users receive a default password when they first are given an account, and must change it immediately. However, no one ever reads the password requirements the first time, and as such, it always takes multiple tries to create a new password.
So, I've created a table like this:
```
<table>
<tr><td align="right">• Not be the same as your old password</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Not be fewer than eight characters in length</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one number</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one uppercase letter</td><td align="left">Not Met</td></tr>
<tr><td align="right">• Contain at least one lowercase letter</td><td align="left">Not Met</td></tr>
</table>
//Later on, inside some <form> tags
<tr><td align="right">Old password: </td><td align="left"><input type="password" id="oldpass" name="oldpass" tabindex="1" /></td></tr>
<tr><td align="right">New password: </td><td align="left"><input type="password" id="newpass1" name="newpass1" tabindex="2" /></td></tr>
<tr><td align="right">New password, again: </td><td align="left"><input type="password" id="newpass2" name="newpass2" tabindex="3" /></td></tr>
```
What I want to have happen is while the user enters text in the fields, JavaScript (I guess) runs in the background and changes the "Not Met" text to "Met" and makes it green or something if the password validates. What is the best way to do this?
TIA. | Off the top of my head, you could create a function that contains all the validation rules you need, e.g:
```
function validatePass()
{
var error = false;
var oldPass = document.getElementById("oldPass").value;
var newPass = document.getElementById("newPass").value;
if(oldPass != newPass) {
error = true;
}
if(error) {
document.getElementById("someCellId").innerText = 'Not Met';
} else {
document.getElementById("someCellId").innerText = 'Met';
}
//set error to false for the next rule
error = false;
//more rules
//possibly using
//regular expressions
//and referencing appropriate
//not met and met table cells
}
```
Attach that to the keydown event of all three text boxes, e.g.:
```
<input type="password" id="oldpass" name="oldpass" tabindex="1" onkeydown="javascript:validatePass()" />
```
That should be a start. | Depending on what javascript framework you are using (if any), the implementation will be different. But the concept will be the same:
1 - You should observe the onchange event of the given text input where the password is being typed.
2 - When the event is triggered, it should call a function that would validate if the password meets the minimum requirement, so you would also need a function to make that validation.
3 - If it does have the minimum requirements just change the text and style of the specific span.
For Prototype JS it would be something like (imagining that the first table you shown had an id for the DOM parsing):
```
function isValid(elem){
// example:
if($(elem).value.length < 8) return false;
return true;
}
$('newpass1').observe('change', function(){
if(isValid('newwpass1'){
// it would be easier and faster with an id in the table cell
var elem = $$('table#tableid td')[8];
elem.innerHTML = 'Met';
elem.setStyle({color:'green'});
}
});
```
You could also use a ready to use solution like [jQuery Validation](http://docs.jquery.com/Plugins/Validation) and skip the in-house coding for all this validations. | How can I dynamically change the style of some text depending on user input? | [
"",
"javascript",
""
] |
I have inherited some code:
```
Process p = new ProcessBuilder("/bin/chmod", "777", path).start();
p.waitFor();
```
Basically, there is for some ancient and highly voodoo based reason for storing key/value pairs on disk as files. I don't really want to go into it.
However, I am left with a bunch of IO exceptions:
```
Exception :Cannot run program "/bin/chmod": java.io.IOException: error=24, Too many open files
Message: Cannot run program "/bin/chmod": java.io.IOException: error=24, Too many open files
```
And by a bunch I mean in the realms of 10k - millions
I get the feeling the waitFor call was to stop these from occurring waiting for the process to complete it and exit back, however I think the chmod is returning a result before the file is actually closed. Does anyone know if that would be the cause of these exceptions?
My other inclination is that the opening and closing of thousands of files is not happening quickly enough on the java end and that there is something else going on, maybe something like that there is some form of file buffer that isn't getting cleared out when fw.close() is being called.
I am pretty new to java and this was a hell weird one that has me stumped. (gladly the app still runs somehow.. after spitting out a very large log file that is)
Can anyone else think of a way to get around this, clearing buffers or increasing the files open limit to something where the jvm can keep up with itself (assuming that is the problem) | I presume you are running these chmod commands in a loop - otherwise I don't see why you'd get so many exceptions. It's possible that you're hitting a deadlock because you're not reading the output of the spawned processes. That certainly used to bite me back in the pre-`ProcessBuilder`, `Runtime.exec()` days.
Change your code snippet to the above pattern:
```
try {
ProcessBuilder pb = new ProcessBuilder("/bin/chmod", "777", path);
pb.redirectErrorStream(true); // merge stdout, stderr of process
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String lineRead;
while ((lineRead = br.readLine()) != null) {
// swallow the line, or print it out - System.out.println(lineRead);
}
int rc = p.waitFor();
// TODO error handling for non-zero rc
}
catch (IOException e) {
e.printStackTrace(); // or log it, or otherwise handle it
}
catch (InterruptedException ie) {
ie.printStackTrace(); // or log it, or otherwise handle it
}
```
(credit: [this site](http://www.csfalcon.com/wiki/csfalcon/ShellCommandsWithJava)) and see if that helps the situation. | Thanks for the help guys, this should sort out a load of weirdness going on elsewhere because of it.
Using your(Vinay) example and the stream closings:
```
try{
fw.close();
ProcessBuilder pb = new ProcessBuilder("/bin/chmod", "777", path);
pb.redirectErrorStream(true); // merge stdout, stderr of process
p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String lineRead;
while ((lineRead = br.readLine()) != null) {
// swallow the line, or print it out - System.out.println(lineRead);
}
} catch (Exception ioe) {
Logger.logException(Logger.WARN, ioe.getMessage(), ioe);
} finally {
try {
p.waitFor();//here as there is some snipped code that was causing a different
// exception which stopped it from getting processed
//missing these was causing the mass amounts of open 'files'
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
} catch (Exception ioe) {
Logger.logException(Logger.WARN, ioe.getMessage(), ioe);
}
}
```
Got the idea from John B Mathews [post](http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/d370f140c9f223a3?pli=1). | Process Builder waitFor() issue and Open file limitations | [
"",
"java",
"java-io",
"processbuilder",
""
] |
Let's say I've got a method that takes some arguments and stores them as instance variables. If one of them is null, some code later on is going to crash. Would you modify the method to throw an exception if null arguments are provided and add unit tests to check that or not? If I do, it's slightly more complicated since javascript has many bad values (null, undefined, NaN, etc.) and since it has dynamic typing, I can't even check if the right kind of object was passed in. | I think it really depends on what sort of API you're unit testing. If this is a component designed and built for internal use only, and you know usage will be under certain constraints, it can be overkill to unit test for bad parameters. On the other hand, if you're talking about something for distribution externally, or which is used in a wide variety of situations, some of which are hard to predict, yes, checking for bad parameters is appropriate. It all depends on usage. | I think you really have 2 different questions here.
The first is what is the best practice for parameter input validation and the second is should your unit test handle test for these situations.
I would recommend that you either throw an Argument Exception for the parameter that was not supplied correctly to your function or some other variable/message that informs the calling function/user of the situation. Normally, you do not want to throw exceptions and should try to prevent the functions from even being called when you know they will fail.
For your unit test, you should definitely include NULL value tests to make sure a graceful result occurs. | How important is checking for bad parameters when unit testing? | [
"",
"javascript",
"unit-testing",
""
] |
I am trying to compile and run a simple java class within eclipse. The compile task works fine, and since I do not specify a destination folder the build files are in the same directory as the source. Which is alright, at the moment all I need is to learn how I can run the class with the main() method.
I have tried using the fully qualified name of the class (with package name, etc) and the classname alone, but always I get a java.lang.ClassNotFoundException
```
Buildfile: C:\Users....\build.xml
run:
[java] java.lang.NoClassDefFoundError: code/control/MyClass
[java] Caused by: java.lang.ClassNotFoundException: code.control.MyClass
[java] at java.net.URLClassLoader$1.run(Unknown Source)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClass(Unknown Source)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClass(Unknown Source)
[java] at java.lang.ClassLoader.loadClassInternal(Unknown Source)
[java] Could not find the main class: code.control.MyClass. Program will exit.
[java] Exception in thread "main"
[java] Java Result: 1
compile:
default:
BUILD SUCCESSFUL
Total time: 234 milliseconds
```
Below, are the targets taken from my build.xml file:
```
<target name="default" depends="compile" description="learn">
</target>
<target name="compile" depends="run">
<javac srcdir="src/" />
</target>
<target name="run">
<java classname="code.control.MyClass" fork="true"/>
</target>
```
I can't figure out why the class is not found. MyClass contains the main() method and since i specify no classpath it should look at the current directory, which is the src/ right?
The development directory is the usual eclipse file structure:
projectName/src/code/control/MyClass
If it is a classpath problem how could I resolve it? I always had problem grasping the concept "put it on your classpath" ... If someone could provide a little bit of explanation with the classpath in the ant context, I would be very thankful.
Thanks for any help on this. The version of ant is 1.7.0 | The [classpath](http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html) is where the Java runtime looks for your .class files, similar to how your OS uses the PATH variable to find executables.
Try this in your build script:
```
<target name="run">
<java fork="true" classname="code.control.MyClass">
<classpath>
<path location="src/"/>
</classpath>
</java>
```
There's a [HelloWorld version for ant](http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html) that walks through building a Java program with ant. | you should include classpath, e.g.
```
<java classpath="${bin}" classname="code.control.MyClass">
```
where ${bin} is your output folder. | ClassNotFoundException with ant's java task and classpath | [
"",
"java",
"ant",
"classpath",
""
] |
I have two pages, NonMember.aspx and Member.aspx. If a user comes to the site, they will go to NonMember.aspx as soon as they login, I want them to immediately be redirected to Member.aspx, but instead of doing this, it is staying on NonMember.aspx. The user actually has to go click on the menu item again to get to Member.aspx.
The links are located at <http://abc.com/tools/NonMember.aspx>
and <http://abc.com/tools/Member.aspx>.
I was doing:
```
System.IO.Path.GetFileNameWithoutExtension(Request.Url.ToString());
```
but I am thinking there is a better way, especially since I have multiple default.aspx pages and this could pose a problem
Here is more detail on what exactly I am doing:
When I run the site on my local development machine, the NonMember page points to:
<http://testserver/tools/NonMember.aspx>.
Requet.Url.AbsolutePath points to /testserver/tools/NonMember.aspx.
Then I am doing this:
```
if(url == "~/tools/NonMember.aspx")
{
Response.Redirect("~/tools/Member.aspx");
}
```
The above is not working and I can check if url is equal to /testserver/tools/NonMember.aspx because if I deploy to liveserver, it will fail. | When using Forms Authentication for an ASP.NET application, it will automatically redirect you to the page you were viewing before you logged in. This is why you are redirected back to the NonMember.aspx page.
It would be better if you had just one member page, and perform a check in the page to see if the user is authenticated, if so, display the member content, otherwise, display the non-member content.
Then, when the user logs in and is redirected back to the page, they will see the member content.
---
If you are insistent on keeping the two separate pages, then in your check you simply have to see if the current user is authenticated (through the IsAuthenticated property on the User that is exposed through the page) and then redirect to your members page. If you are on the NonMember page, you don't need to check to see what the url is (unless this is MVC, which you didn't indicate). | If you have the HttpResponse object, you can use HttpResponse.Redirect | How to direct to a member page from a non-member page when a user logs in? | [
"",
"c#",
"asp.net",
"authentication",
""
] |
I'm using Spring to handle RMI calls to some remote server. It is straightforward to construct an application context and obtain the bean for remote invocations from within the client:
```
ApplicationContext context = new ApplicationContext("classpath:context.xml");
MyService myService = (MyService ) context.getBean( "myService " );
```
However I don't see a simple way to pass properties into the configuration. For example if I want to determine the host name for the remote server at runtime within the client.
I'd ideally have an entry in the Spring context like this:
```
<bean id="myService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://${webServer.host}:80/MyService"/>
<property name="serviceInterface" value="com.foo.MyService"/>
</bean>
```
and pass the properties to the context from the client as a parameter.
I can use a PropertyPlaceholderConfigurer in the context to substitute for these properties, but as far as I can tell this only works for properties read from a file.
I have an implementation that addresses this (added as an answer) but I'm looking for a standard Spring implementation to avoid rolling my own. Is there another Spring configurer (or anything else) to help initialise the configuration or am I better off looking at java config to achieve this? | *Update*:
Based on the question update, my suggestion is:
1. Create a `ServiceResolver` bean which handles whatever you need to handle based on client input;
2. Declare this bean as a dependency to the relevant services;
3. At runtime, you may update / use this bean however you see fit.
The `ServiceResolver` can then, either on the `init-method` or on each invocation determine the values to return to the client, based on e.g. JNDI lookups or enviroment variables.
But before doing that, you might want to take a look at the [configuration options](http://static.springsource.org/spring/docs/2.5.x/reference/xsd-config.html) available. You can either:
* add property files which don't have to be present at compile-time;
* look up values from JNDI;
* get values from the System.properties.
---
If you need to lookup properties from a custom location, take a look at `org.springframework.beans.factory.config.BeanFactoryPostProcessor` and how the `org.springframework.beans.factory.config.PropertyPlaceholderConfigurer` is implemented.
The basic idea is that you get the beans with the 'raw' properties, e.g. `${jdbcDriverClassName}` and then you get to resolve them and replace them with the desired values. | See <http://forum.springsource.org/showthread.php?t=71815>
> `TestClass.java`
>
> ```
> package com.spring.ioc;
>
> public class TestClass {
>
> private String first;
> private String second;
>
> public String getFirst() {
> return first;
> }
>
> public void setFirst(String first) {
> this.first = first;
> }
>
> public String getSecond() {
> return second;
> }
>
> public void setSecond(String second) {
> this.second = second;
> }
> }
> ```
>
> `SpringStart.java`
>
> ```
> package com.spring;
>
> import java.util.Properties;
>
> import com.spring.ioc.TestClass;
> import org.springframework.context.support.ClassPathXmlApplicationContext;
> import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
>
> public class SpringStart {
> public static void main(String[] args) throws Exception {
> PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
> Properties properties = new Properties();
> properties.setProperty("first.prop", "first value");
> properties.setProperty("second.prop", "second value");
> configurer.setProperties(properties);
>
> ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
> context.addBeanFactoryPostProcessor(configurer);
>
> context.setConfigLocation("spring-config.xml");
> context.refresh();
>
> TestClass testClass = (TestClass)context.getBean("testBean");
> System.out.println(testClass.getFirst());
> System.out.println(testClass.getSecond());
> }
> }
> ```
>
> `spring-config.xml`
>
> ```
> <?xml version="1.0" encoding="UTF-8"?>
> <beans xmlns="http://www.springframework.org/schema/beans"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xsi:schemaLocation="
> http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
>
> <bean id="testBean" class="com.spring.ioc.TestClass">
> <property name="first" value="${first.prop}"/>
> <property name="second" value="${second.prop}"/>
> </bean>
>
> </beans>
> ```
>
> Output:
>
> ```
> first value
> second value
> ``` | Passing properties to a Spring context | [
"",
"java",
"spring",
"rmi",
""
] |
I came across something very basic but extremely bewildering today. I needed to convert a list to an array. The list contained `String` instances. Perfect example of using `List.toArray(T[])`, since I wanted a `String[]` instance. It would not work, however, without explicitly casting the result to `String[]`.
As a test scenario, I used the following code:
```
import java.util.Arrays;
import java.util.List;
public class MainClass {
public static void main(String args[]) {
List l = Arrays.asList("a", "b", "c");
String stuff[] = l.toArray(new String[0]);
System.err.println(Arrays.asList(stuff));
}
}
```
which does not compile. It's nearly an exact copy of the example in the [javadoc](http://java.sun.com/javase/6/docs/api/java/util/List.html#toArray(T[])), yet the compiler says the following:
```
MainClass.java:7: incompatible types
found : java.lang.Object[]
required: java.lang.String[]
String stuff[] = l.toArray(new String[0]);
^
```
If I add a cast to `String[]` it will compile AND run perfectly. But that is not what I expect when I looked at the signature of the toArray method:
```
<T> T[] toArray(T[] a)
```
This tells me that I shouldn't have to cast. What is going on?
Edit:
Curiously, if I change the list declaration to:
```
List<?> l = Arrays.asList("a", "b", "c");
```
it also works. Or `List<Object>`. So it doesn't have to be a `List<String>` as was suggested. I am beginning to think that using the raw `List` type also changes how generic methods inside that class work.
Second edit:
I think I get it now. What Tom Hawtin wrote in a comment below seems to be the best explanation. If you use a generic type in the raw way, all generics information from that instance will be erased by the compiler. | you forgot to specify the type parameter for your List:
```
List<String> l = Arrays.asList("a", "b", "c");
```
in this case you can write safety:
```
String[] a = l.toArray(new String[0]);
```
without any cast. | or do
```
List<?> l = Arrays.asList("a", "b", "c");
```
*still strange* | Odd generics behaviour of List.toArray(T[]) | [
"",
"java",
"arrays",
"list",
""
] |
I am trying to locate a key in a HashMap. I can print the selected key by using 'get' but when I use 'containsKey' in an if statement, it is not found.
I KNOW the key is present in the Map but it keeps returning false. Any ideas people?
My code:
```
public static boolean checkLowerStructuralSupport(Location location) {
boolean hasSupport = false;
Location supportingLocation = new Location(location.getX(), location.getY(), location.getZ() - 1);
System.out.println(_levels.get(supportingLocation.getZ()).getLevelSites2().get(supportingLocation)); //works
if (_levels.get(supportingLocation.getZ()).getLevelSites2().containsKey(supportingLocation)) {
hasSupport = true;
} else {
hasSupport = false;
}
return hasSupport;
}
```
Here is the code for the Location class:
```
public class Location {
protected int _x;
protected int _y;
protected int _z;
public Location(int xAxis, int yAxis, int zAxis) {
this._x = xAxis;
this._y = yAxis;
this._z = zAxis;
}
public void equals() {
//not implemented yet
}
public void HashCode() {
//not implemented yet
}
public String toString() {
String locationString = Integer.toString(_x) + Integer.toString(_y) + Integer.toString(_z);
return locationString;
}
public void setX(int XAxis) {
this._x = XAxis;
}
public int getX() {
return this._x;
}
public void setY(int YAxis) {
this._y = YAxis;
}
public int getY() {
return this._y;
}
public void setZ(int ZAxis) {
this._z = ZAxis;
}
public int getZ() {
return this._z;
}
}
``` | You must ensure that the `Location` class has properly implemented its `hashCode()` and `equals(Object)` methods ([documentation](http://java.sun.com/javase/6/docs/api/java/lang/Object.html)). That is, if two `Location` objects are effectively equal, they should share a common hash code and their `equals` method should return `true`. | As descibed here, you have to override the **equals(Object)** method.
The reason why get(Object) is working is, that HashMap will calculate the Hash for your Location class and returns the Object the hascode points to.
containsKey(Object) calculates the hash key and gets the object the hash is pointed to. The object from the HashMap will compare to the Object you put in. For these comparison the equals method is used.
When you do not override he equals method, true is returned, when the object reference to the same instance.
**From HashMap**
```
/**
* Check for equality of non-null reference x and possibly-null y.
*/
static boolean eq(Object x, Object y) {
return x == y || x.equals(y);
}
```
**From Object**
```
public boolean equals(Object obj) {
return (this == obj);
}
```
From the javadoc of equals
> The equals method for class Object
> implements the most discriminating
> possible equivalence relation on
> objects; that is, for any non-null
> reference values x and y, this method
> returns true if and only if x and y
> refer to the same object (x == y has
> the value true).
>
> **Note that it is generally necessary to
> override the hashCode method whenever
> this method is overridden, so as to
> maintain the general contract for the
> hashCode method, which states that
> equal objects must have equal hash
> codes.** | Java HashMap get works but containsKey does not | [
"",
"java",
"hashmap",
""
] |
I have:
```
void add_all_msgs(std::deque<Message>::iterator &iter);
```
How can I make that function "generic", so it can take any kind of inputiterators ? I don't really care if it's iterating a deque,a vector or something else, as long as the iterator is iterating Message's. - is this at all straight forward possible in c++ ? | ```
template<class InputIterator>
void add_all_msgs(InputIterator iter);
```
Usage:
```
std::deque<Message> deq;
add_all_msgs(deq.begin());
``` | ```
template <typename Iterator>
void add_all_messages(Iterator first, Iterator last)
```
usage :
```
vector<message> v;
add_all_messages(v.begin(), v.end());
```
You need to specify the end, otherwise you won't know when to stop! It also gives you the flexibility of adding only a subrange of a container. | "Generic" iterator in c++ | [
"",
"c++",
"stl",
"iterator",
""
] |
I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).
Here's what I want to use for URLs:
```
/item/value/0.01
/item/value/0.05
```
Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and pass the value in cents so it would be /item/value/1, but I'd like to receive the argument in my view as a decimal data type rather than as an integer (and I may have to deal with fractions of a cent at some point). Is it possible to write a regex in a Django URL pattern that will handle this? | It can be something like
```
urlpatterns = patterns('',
(r'^item/value/(?P<value>\d+\.\d{2})/$', 'myapp.views.byvalue'),
... more urls
)
```
url should not start with slash.
in views you can have function:
```
def byvalue(request,value='0.99'):
try:
value = float(value)
except:
...
``` | I don't know about Django specifically, but this should match the URL:
```
r"^/item/value/(\d+\.\d+)$"
``` | How Do I Use A Decimal Number In A Django URL Pattern? | [
"",
"python",
"regex",
"django",
"django-urls",
""
] |
I'm having some trouble with IE6 and jQuery UI. I have a popup dialog (modal, if it matters), that displays a "yes/no" dialog to the user with some information. In order to facilitate this, I build the dialog with autoOpen = false, and then I call $('#popup').show() later on as needed, in response to various different events. Now, in IE6 (and only IE6, as far as I can tell), the .dialog method will occasionally fail but STILL return the jQuery object. So, rather than show a popup, the .show() method just display a div container in the html page.
What could be causing this, and how I can fix this behavior?
Thanks.
```
$('#myDialog').dialog({
autoOpen: false,
buttons: {
"No": function()
{
$(this).dialog('close');
//do stuff
},
"Yes": function()
{
$(this).dialog('close');
//do stuff
}
},
draggable: false,
modal: true,
resizable: false,
title: "Confirmation",
width: "500px",
zIndex: 2000
});
```
and later
```
$('#myDialog').dialog('open').show();
```
Pretty standard.
**New information**
I'm loading the page that makes the dialog with ajax inside of another dialog, which can be repeatedly created and destroyed. Now, each time my page gets loaded with ajax, .dialog(opts) should re-instantiate the dialog div, correct? I've found that this is the scenario.
1.) An outer dialog uses ajax to replace its content with my content.
2.) My content launches a dialog that was previously created and set to not autoopen.
3.) The outer dialog is destroyed as the inner dialog is closed.
4.) The outer dialog is reopened. The inner dialog no longer is able to appear as a dialog in ie6. This ONLY happens in ie6. | I had a similar situation and was never able to reuse the dialog. I had to destroy and recreate both dialogs each time. | You should open your dialog using
```
$('#myDialog').dialog('open');
```
instead of
```
$('#myDialog').show();
```
The first method displays actual dialog box, while the one you are using just causes the `#myDialog` item to be displayed (with no UI Dialog magic). `show()` method is the part of the core jQuery library and shoudn't be used to invoke a dialog. | jQuery UI .dialog() method failing silently in IE6 | [
"",
"javascript",
"jquery",
"jquery-ui",
"internet-explorer-6",
""
] |
I have a std::vector. I want to create iterators representing a slice of that vector. How do I do it? In pseudo C++:
```
class InterestingType;
void doSomething(slice& s) {
for (slice::iterator i = s.begin(); i != s.end(); ++i) {
std::cout << *i << endl;
}
}
int main() {
std::vector v();
for (int i= 0; i < 10; ++i) { v.push_back(i); }
slice slice1 = slice(v, 1, 5);
slice slice2 = slice(v, 2, 4);
doSomething(slice1);
doSomething(slice2);
return 0;
}
```
I would prefer not to have to copy the elements to a new datastructure. | You'd just use a pair of iterators:
```
typedef std::vector<int>::iterator vec_iter;
void doSomething(vec_iter first, vec_iter last) {
for (vec_iter cur = first; cur != last; ++cur) {
std::cout << *cur << endl;
}
}
int main() {
std::vector v();
for (int i= 0; i < 10; ++i) { v.push_back(i); }
doSomething(v.begin() + 1, v.begin() + 5);
doSomething(v.begin() + 2, v.begin() + 4);
return 0;
}
```
Alternatively, the Boost.Range library should allow you to represent iterator pairs as a single object, but the above is the canonical way to do it. | I learnt Python before I learnt C++. I wondered if C++ offered slicing of vectors like slicing in Python lists. Took a couple of minutes to write this function that allows you to slice a vector analogous to the way its done in Python.
```
vector<int> slice(const vector<int>& v, int start=0, int end=-1) {
int oldlen = v.size();
int newlen;
if (end == -1 or end >= oldlen){
newlen = oldlen-start;
} else {
newlen = end-start;
}
vector<int> nv(newlen);
for (int i=0; i<newlen; i++) {
nv[i] = v[start+i];
}
return nv;
}
```
### Usage:
```
vector<int> newvector = slice(vector_variable, start_index, end_index);
```
The start\_index element will be included in the slice, whereas the end\_index will not be included.
### Example:
For a vector **v1** like {1,3,5,7,9}
slice(v1,2,4) returns {5,7} | Slicing a vector | [
"",
"c++",
"stl",
""
] |
Has anyone managed to get administration rights through the UAC without restarting the application or embedding a manifest file?
I'd like to write to some files that only administrators can modify, without relying to another elevated application. Is it possible to impersonate an administrator previously calling with some native API the UAC prompt?
I guess this is not possible and I'll have to use an external tool with elevated rights, but I'm asking just in case.
EDIT: I know there are some other similar questions around, but since they do not cover the topic of impersonation (as fas as I've seen), nor some possible native call to the UAC prompt I decided to give a new thread a go... | As stated in this other question, it is not possible, you have can eleveate COM object or another process, but not the current process.
[Request Windows Vista UAC elevation if path is protected?](https://stackoverflow.com/questions/17533/request-vista-uac-elevation-if-path-is-protected/17544#17544) | I read that thread (along with a lot more heh), but you never know what other people has managed to do recently. And maybe the release of SP2 changed something, dunno. | Elevation without restarting an application? | [
"",
"c#",
".net",
"vb.net",
"uac",
""
] |
Is there a way to annotate a method so all exceptions thrown are converted to runtime exception automagically?
```
@MagicAnnotation
// no throws clause!
void foo()
{
throw new Exception("bar")'
}
``` | No way to do that, at least for now I use workaround like this (simplified):
```
@SuppressWarnings({"rawtypes", "unchecked"})
public class Unchecked {
public static interface UncheckedDefinitions{
InputStream openStream();
String readLine();
...
}
private static Class proxyClass = Proxy.getProxyClass(Unchecked.class.getClassLoader(), UncheckedDefinitions.class);
public static UncheckedDefinitions unchecked(final Object target){
try{
return (UncheckedDefinitions) proxyClass.getConstructor(InvocationHandler.class).newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target instanceof Class){
return MethodUtils.invokeExactStaticMethod((Class) target, method.getName(), args);
}
return MethodUtils.invokeExactMethod(target, method.getName(), args);
}
});
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
```
And the usage looks like:
```
import static ....Unchecked.*;
...
Writer w = ...;
unchecked(w).write(str, off, len);
```
The trick is that interface is "never finished" and everytime I need unchecked method somewhere, I'll wrap that object into unchecked and let IDE generate method signature in interface.
Implementation is then generic (reflective and "slow" but usually fast enough)
There are some code post-processors and bytecode-weavers but this was not possible (not even aop or other jvm based language) for my current project, so this was "invented". | Project Lombok's [`@SneakyThrows`](http://projectlombok.org/features/SneakyThrows.html) is probably what you are looking for. Is not really wrapping your exception (because it can be a problem in a lot of cases), it just doesn't throw an error during compilation.
```
@SneakyThrows
void foo() {
throw new Exception("bar")'
}
``` | Wrap exceptions by runtime exceptions with an annotation | [
"",
"java",
"exception",
"annotations",
"runtimeexception",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.