Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
TextBoxes created by "CreateWindowEx(WS\_EX\_CLIENTEDGE, "EDIT", "", ES\_MULTILINE.."
require \r\n for a new line.
im redirecting my stdoutput into that textbox, which uses just '\n' to indicate a new line. and im not willing to replace all '\n' with '\r\n'
isn't there a way to let '\n' beeing a newline in textboxes?
thx | I'm pretty sure what you're asking is impossible (i.e. there's no magic setting to make Windows edit controls accept Unix-style newlines). | Not sure what language you are using, but why not just do this (VB.NET Example):
```
TextBox1.Text=TextBox1.Text.Replace("\r\n","\n")
```
That should replace all the "\r\n" occurences with just "\n" | TextBox let '\n' be the carriage return | [
"",
"c++",
"winapi",
""
] |
When writing a JSP file, how can I get the **current directory** of this file at runtime
(to be able to iterate the directory and list its contents)?
Would some file I/O operations be restricted because of some security issues?
*I would prefer a solution without accessing some implementation-specific
server variables / properties.*
**EDIT:**
I wouldn't ask if it were as simple as *`new File(".")`*, because this would just give the directory of server's executables. | you should know the path of the jsp within your web application so you can pass that to getRealPath()
```
File jsp = request.getRealPath(pathToJspInWebapp); //eg. /WEB-INF/jsp/my.jsp
File directory = jsp.getParentFile();
File[] list = directory.listFiles();
``` | ```
<%@page import="java.io.*" %>
<%@page import="java.util.*" %>
<%! public void GetDirectory(String a_Path, Vector a_files, Vector a_folders) {
File l_Directory = new File(a_Path);
File[] l_files = l_Directory.listFiles();
for (int c = 0; c < l_files.length; c++) {
if (l_files[c].isDirectory()) {
a_folders.add(l_files[c].getName());
} else {
a_files.add(l_files[c].getName());
}
}
}
%>
<%
Vector l_Files = new Vector(), l_Folders = new Vector();
GetDirectory("C:/mydirectory/", l_Files, l_Folders);
//folders should be left out...
//for( int a = 0 ; a<l_Folders.size() ; a++ )
//out.println( "[<b>"+l_Folders.elementAt(a).toString() + "</b>]<br>") ;
//generate files as XML
out.println("<music>");
for (int a = 0; a < l_Files.size(); a++) {
out.println("<file>" + l_Files.elementAt(a).toString() + "</file>");
}
out.println("</music>");
%>
```
Replace **"C:/mydirectory/"** with your directory | How to list contents of a server directory using JSP? | [
"",
"java",
"jsp",
"file",
""
] |
```
public void populateNotesFromFile()
{
try{
BufferedReader reader = new BufferedReader(new FileReader(DEFAULT_NOTES_SAVED));
String fileNotes = reader.readLine();
while(fileNotes != null){
notes.add(fileNotes);
fileNotes = reader.readLine();
}
reader.close();
}
catch (IOException e){
System.err.println("The desired file " + DEFAULT_NOTES_SAVED + " has problems being read from");
}
catch (FileNotFoundException e){
System.err.println("Unable to open " + DEFAULT_NOTES_SAVED);
}
//make sure we have one note
if (notes.size() == 0){
notes.add("There are no notes stored in your note book");
}
}
```
Whenever i compile the above i get a message saying cannot find symbol class IOException e
can someone tell me how to fix it please :d
thanks | IOException is a class from the java.io package, so in order to use it, you should add an `import` declaration to your code. `import java.io.*;` (at the very top of the java file, between the package name and your class declaration)
FileNotFoundException *is a* IOException. It's a specialisation of IOException. Once you have caught the IOException, the flow of the program will never get to the point of checking for a more specific IOException. Just swap these two, to test for the more specific case first (FileNotFound) and *then* handle (catch) any other possible IOExceptions. | Your probably missing an `import` reference to `IOException` `class`. I'ts located in the `java.io` package.
Can I suggest a litle change in you method? Always close the stream in a finally block:
```
public void populateNotesFromFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(DEFAULT_NOTES_SAVED));
String fileNotes = reader.readLine();
while (fileNotes != null) {
notes.add(fileNotes);
fileNotes = reader.readLine();
}
} catch (FileNotFoundException e) {
System.err.println("Unable to open " + DEFAULT_NOTES_SAVED);
} catch (IOException e) {
System.err.println("The desired file " + DEFAULT_NOTES_SAVED
+ " has problems being read from");
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// make sure we have one note
if (notes.size() == 0) {
notes.add("There are no notes stored in your note book");
}
}
``` | cannot find symbol class IOException | [
"",
"java",
"exception",
""
] |
I'm wondering if it's possible to debug a command line application (where main received arguments argc, and \*\*argv) in visual studio 2008? | You can easily set the command arguments to the executable from within Visual Studio, in the Debugging screen under Configuration Properties (at least that's where it is in 2005). | Yes; it works the same way as in a GUI application. Set a breakpoint somewhere, and hit debug start. | debug command line application | [
"",
"c++",
"visual-studio-2008",
"debugging",
""
] |
What are the different ways you can control/read the Scrollbar in a web browser with *JavaScript*, apart from anchors? -- Unless you can dynamically create anchors and tell the browser to scroll down to that. | To scroll by an arbitrary amount:
```
//Parameters being the amount by which to scroll in pixels (horizontal and vertical)
window.scrollBy(50, 50);
```
To scroll to a certain point:
```
window.scrollTo(0, 30);
```
To read current position:
```
document.body.scrollLeft
document.body.scrollTop
``` | [Here is one example](http://www.sitepoint.com/article/preserve-page-scroll-position/) of how you can control X/Y scrolling without anchors. ( ScrollX/ScrollY)
The key part I suppose is the following
```
function saveScrollCoordinates() {
document.Form1.scrollx.value = (document.all)?document.body.scrollLeft:window.pageXOffset;
document.Form1.scrolly.value = (document.all)?document.body.scrollTop:window.pageYOffset;
}
``` | How to scroll to show a part of a webpage | [
"",
"javascript",
"dynamic",
"scroll",
"browser",
""
] |
I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:
```
val = ''.join([c for c in val if c in '1234567890.'])
```
What would you do? | You can use a regular expression (using the [**`re`**](https://docs.python.org/2/library/re.html) module) to accomplish the same thing. The example below matches runs of `[^\d.]` (any character that's not a decimal digit or a period) and replaces them with the empty string. Note that if the pattern is compiled with the `UNICODE` flag the resulting string could still include [non-ASCII numbers](http://www.fileformat.info/info/unicode/category/Nd/list.htm). Also, the result after removing "non-numeric" characters is not necessarily a valid number.
```
>>> import re
>>> non_decimal = re.compile(r'[^\d.]+')
>>> non_decimal.sub('', '12.34fe4e')
'12.344'
``` | Another 'pythonic' approach
`filter( lambda x: x in '0123456789.', s )`
but regex is faster. | Strip all non-numeric characters (except for ".") from a string in Python | [
"",
"python",
""
] |
how do I get the fields of a column that's without a match in another column?
I tried:
```
SELECT table1.page_title
FROM table1, table2
WHERE table1.page_title != table2.page_title
```
It produces a lot of duplicate fields so I did a:
```
SELECT DISTINCT table1.page_title
FROM table1, table2
WHERE table1.page_title != table2.page_title
```
but it just hangs.
Any help would be greatly appreciated, thanks!
P.S.
I'm doing this so I could create an exclude list for mediawiki's MWDumper tool. I need it so that when I import the outputted sql, my current wiki entries will not be overwritten.
EDIT:
Yes they're 2 different tables. Each has about 70,000+ records
Also why are my queries slow? I'd appreciate it if someone could clarify so I could learn why :) Thanks again! | Are a and b different tables, both having a "page\_title" column?
If so, try this:
```
SELECT DISTINCT page_title FROM a
WHERE page_title NOT IN (SELECT page_title FROM b)
```
If all you're interested in is removing duplicates (if you only have one table), then there are several ways to do it, two of which are:
```
SELECT DISTINCT page_title FROM a
```
or
```
SELECT page_title FROM a
GROUP BY page_title
```
The GROUP BY option is stronger albeit slower - you can add a HAVING clause to choose only those titles that appear e.g. more than twice:
```
SELECT page_title FROM a
GROUP BY page_title
HAVING COUNT(page_title) > 2
```
Hope that helps
(Thanks Aaron F for the comment) | You could try a self-join, which I have used in the past, but I am not sure if that would be any faster, as I don't use MySQL. This page might give you some insight: <http://www.xaprb.com/blog/2006/10/11/how-to-delete-duplicate-rows-with-sql/> | Fast way to get the difference of 2 columns in MySQL | [
"",
"sql",
"mysql",
"mediawiki",
""
] |
I'm trying to write some c++ classes for interfacing with LUA and I am confused about the following:
In the following example: Wherigo.ZCommand returns a "Command" objects, also zcharacterFisherman.Commands is an array of Command objects:
With the following LUA code, I understand it and it works by properly (luaL\_getn returns 3 in the zcharacterFisherman.Commands c++ set newindex function):
```
zcharacterFisherman.Commands = {
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
```
But when the array is defined with the following LUA code with a slightly different syntax luaL\_getn returns 0.
```
zcharacterFisherman.Commands = {
Talk = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Talk2 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Talk3 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
```
All objects are defined in c++ and the c++ objects hold all the object members so I am trying to just connect LUA to those c++ objects. Is this enough or do I need to post some of my code?? | luaL\_getn is for getting the highest numeric element of an *array* in Lua. An array is a table with only integer indices. When you define a table in Lua (the first example) without explicitly setting indices, you will get an array with elements 1, 2, and 3. Naturally, luaL\_getn returns a 3 here. luaL\_getn is NOT defined to return the number of elements in the table, it is defined to return the highest numeric index in the table (see <http://www.lua.org/manual/5.1/manual.html#pdf-table.maxn>)
The second example is NOT using numeric indices, and this table is not a Lua array -- it is more like a hash table. Since luaL\_getn only works on true arrays, you wouldn't expect it to work here.
Unfortunately, there is no simple way to get the number of elements in a table (lua\_objlen solves a related problem, but does not fix this one). The only way to do it is to either:
1. Always use array notation. Don't ever use anything else as the keys in your table. You will get a lot of speed-ups this way.
2. Iterate through your table and count the number of elements when you wish to know the table's size. The language does not provide a one-line method for getting the size of a full table, since general tables are implemented using hashes and do not track their element count. | ### Lua is correct.
Your first example is forming a table that contains exactly three entries with indices 1, 2, and 3, none of which are specified explicitly. In this case `table.maxn()`, the `#` operator, and `lua_objlen()` all agree that there are three array elements.
Your second example is forming a table that contains exactly three entries with indices "Talk", "Talk2", and "Talk3", all specified explicitly but none are integers. In this case, `table.maxn()`, the `#` operator, and `lua_objlen()` all agree that there are zero array elements.
### Why is this the right answer?
A Lua `table` is an associative array that can map values of any type (except `nil`) to values of any type (again, except `nil`). There is no other general container type in Lua, so tables are used for essentially everything. The implementation is not part of the Lua specification, but in practice a table is indexed as a hash table, and there is no natural ordering of the keys.
However, a common use case for tables is as a container that acts like a conventional array. Such a container has contiguous integer indices, and can be iterated in order. The table implementation makes this particularly efficient for integer keys starting at `1`. These entries in the table are physically allocated as a contiguous array, and the keys are neither hashed nor stored. This saves storage space both in allocation overhead and by not storing some of the keys at all. It also saves run time since access is by direct calculation rather than by computing a hash and verifying the matching value.
Since arrays are just tables, the table initializer syntax has been designed to make that case easy and clear, as well as to support the other common use case where keys are strings that happen to be valid identifiers.
### Lua 5.1 vs. Lua 5.0
In the current release of Lua (5.1.4, but this is true of all 5.1 releases) the Lua 5.0 functions `table.getn()`, `table.setn()`, `luaL_getn()`, and `luaL_setn()` are all [deprecated](http://www.lua.org/manual/5.1/manual.html#7), as is the common usage of a table field `n` for an array to indicate its array length. The `table.getn()` function is replaced by the `#` operator, and `luaL_getn()` by `lua_objlen()`. There is no equivalent to the `setn()` functions since Lua now manages the array size behind the scenes.
The `#` operator is defined on a table to return an integer such that indexing the table by the next larger integer returns `nil`. For an empty array (e.g. `a = {}`), it returns 0 because `a[1] == nil`. For a normal array, it returns the largest index in use. However, if an array has holes (missing elements) then it can return the index preceding any hole or the last index in use. If the actual largest integer index in use is required, the new function `table.maxn()` can be used, but it has to iterate over all table entries to find that maximum value and thus should only be used when using `#` can't.
This leads to a now common idiom for adding elements to an array: `a[#a+1] = "some new value"`. This idiom is now often recommended in place of `table.insert()` for extending tables. | Lua / c++ problem handling named array entries | [
"",
"c++",
"lua",
""
] |
Currently my WPF application imports a part like this
```
[Import(typeof(ILedPanel)]
public ILedPanel Panel { get; set; }
```
But this gives ma a single intance of the class that implements ILedPanel.
What I really want to do is have the ability to create as many instances
that I need. Please note there is only one Export for ILedPanel included
with the software at any given time.
(If I use an import with List that gives me one instance
for every class implementing ILedPanel)
Any suggestions? | There isn't "built in" support for this in MEF today, but before reverting to Service Locator, you might find some inspiration here: <http://blogs.msdn.com/nblumhardt/archive/2008/12/27/container-managed-application-design-prelude-where-does-the-container-belong.aspx>
The essential idea is that you 'import' the container into the component that needs to do dynamic instantiation.
More direct support for this scenario is something we're exploring.
Nick
**UPDATE:** MEF now has experimental support for this. See [this blog post](http://blogs.msdn.com/nblumhardt/archive/2009/08/28/dynamic-part-instantiation-in-mef.aspx) for more information. | All of the other answers are pretty old, so they don't mention a relatively new feature in MEF called [`ExportFactory`](http://msdn.microsoft.com/en-us/library/ff382807(v=vs.110).aspx). This generic class allows you to import `ExportFactory<ILedPanel>` and create as many instances as you like whenever you need them, so your code would look like this:
```
[Import(typeof(ILedPanel)]
public ExportFactory<ILedPanel> PanelFactory { get; set; }
public ILedPanel CreateNewLedPanelInstance()
{
return PanelFactory.CreateExport().Value;
}
```
This method also satisfies any imports that created part has. You can read more about using the `ExportFactory` class [here](https://mef.codeplex.com/wikipage?title=PartCreator). | Creating multiple instances of Imported MEF parts | [
"",
"c#",
".net",
"mef",
""
] |
I am new to c++ and I have been practicing collision in a small game program that does nothing and I just can't get the collision right
So I use images loaded into variables
```
background = oslLoadImageFile("background.png", OSL_IN_RAM, OSL_PF_5551);
sprite = oslLoadImageFile("sprite.png", OSL_IN_RAM, OSL_PF_5551);
bush = oslLoadImageFile("bush.png", OSL_IN_RAM, OSL_PF_5551);
```
While there are variables stored like
```
sprite->x = 3;
if ( (sprite->x + spritewidth > bush->x) && (sprite->x < bush->x + bushwidth) && (sprite->y + spriteheight > bush->y) && (sprite->y < bush->y + bushheight) )
{
bushcol = 1;
}
else
{
bushcol = 0;
}
```
So when i press a button
```
if (osl_keys->held.down)
{
if (bushcol == 1)
{
sprite->y = bush->y + 38;
}
else
{
sprite->y += 3;
}
}
if (osl_keys->held.up)
{
if (bushcol == 1)
{
sprite->y = bush->y - 23;
}
else
{
sprite->y -= 3;
}
}
if (osl_keys->held.right)
{
if (bushcol == 1)
{
sprite->x = bush->x - 28;
}
else
{
sprite->x += 3;
}
}
if (osl_keys->held.left)
{
if (bushcol == 1)
{
sprite->x = bush->x + 28;
}
else
{
sprite->x -= 3;
}
}
```
i was thinking of things like
```
sprite->y = bushheight - 24;
```
but it doesnt work
Any suggestions? | I think you have the basic idea. Just check your work. Here is a simple version which compiles:
```
#import <stdlib.h>
typedef struct {
// I'm going to say x, y, is in the center
int x;
int y;
int width;
int height;
} Rect;
Rect newRect(int x, int y, int w, int h) {
Rect r = {x, y, w, h};
return r;
}
int rectsCollide(Rect *r1, Rect *r2) {
if (r1->x + r1->width/2 < r2->x - r2->width/2) return 0;
if (r1->x - r1->width/2 > r2->x + r2->width/2) return 0;
if (r1->y + r1->height/2 < r2->y - r2->height/2) return 0;
if (r1->y - r1->height/2 > r2->y + r2->height/2) return 0;
return 1;
}
int main() {
Rect r1 = newRect(100,200,40,40);
Rect r2 = newRect(110,210,40,40);
Rect r3 = newRect(150,250,40,40);
if (rectsCollide(&r1, &r2))
printf("r1 collides with r2\n");
else
printf("r1 doesnt collide with r2\n");
if (rectsCollide(&r1, &r3))
printf("r1 collides with r3\n");
else
printf("r1 doesnt collide with r3\n");
}
``` | I'd suggest making a function solely for the purpose of bounding box colision detection.
It could look like
```
IsColiding(oslImage item1, oslImage item2)
{
/* Perform check */
}
```
in which you perform the check if there is a collision between image 1 and image 2.
As for the algorithm you're trying to use check out this wikipedia for example [AABB bounding box](http://en.wikipedia.org/wiki/Bounding_volume#Basic_intersection_checks)
Especially this part:
> In the case of an AABB, this tests
> becomes a simple set of overlap tests
> in terms of the unit axes. For an AABB
> defined by M,N against one defined by
> O,P they do not intersect if (Mx>Px)
> or (Ox>Nx) or (My>Py) or (Oy>Ny) or
> (Mz>Pz) or (Oz>Nz). | Collision-Detection methods in C++ | [
"",
"c++",
"graphics",
"collision",
""
] |
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like `script` I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach? | [IPython](https://ipython.org/) is extremely useful if you like using interactive sessions. For example for your use-case there is [the `%save` magic command](http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-save), you just input `%save my_useful_session 10-20 23` to save input lines 10 to 20 and 23 to `my_useful_session.py` (to help with this, every line is prefixed by its number).
Furthermore, the documentation states:
> This function uses the same syntax as [%history](http://ipython.readthedocs.io/en/5.x/interactive/magics.html#magic-history) for input ranges, then saves the lines to the filename you specify.
This allows for example, to reference older sessions, such as
```
%save current_session ~0/
%save previous_session ~1/
```
Look at [the videos on the presentation page](https://ipython.org/presentation.html) to get a quick overview of the features. | From Andrew Jones's website ([archived](https://web.archive.org/web/20130218140009/http://www.andrewhjon.es:80/save-interactive-python-session-history)):
```
import readline
readline.write_history_file('/home/ahj/history')
``` | How to save a Python interactive session? | [
"",
"python",
"shell",
"read-eval-print-loop",
"interactive-session",
""
] |
how can I convert this string:
`bKk_035A_paint-House_V003`
to
`BKK_035a_paint-House_v003`
with a regular expression (e.g. Regex.Replace)?
This regex matches the string:
```
^(?<Group1>[a-z][a-z0-9]{1,2})_(?<Group2>\d{3}[a-z]{0,2})_(?<Group3>[a-z-]+)_(?<Group4>v\d{3,5})$
```
* Group1 = uppercase
* Group2 = lowercase
* Group3 = unchanged
* Group4 = lowercase
Thanks for any help,
Patrick | the Regex doesn't match the first string...
I assume you want the first 3 chars upper case, and the rest lowercase?
here's a first pass:
```
const string mod = @"^([a-z][a-z0-9]{1,2})(_\d{3}[a-z]{0,2}_[a-z]+_v{1}\d{3,5})$";
var converted =
new Regex(mod, RegexOptions.IgnoreCase)
.Replace(input1,
m => string.Format(
"{0}_{1}",
m.Groups[1].ToString().ToUpper(),
m.Groups[2].ToString().ToLower()
)
);
``` | Another alternative using `Split` and `Join` methods.
```
const string input = "bKk_035A_paint-House_V003";
string[] strParts = input.Split('_');
strParts[0] = strParts[0].ToUpperInvariant();
strParts[1] = strParts[1].ToLowerInvariant();
strParts[3] = strParts[3].ToLowerInvariant();
string result = String.Join("_", strParts);
``` | Use C# regex to convert casing in a string | [
"",
"c#",
"regex",
"string",
""
] |
I recently had an interview at a small company that wants to greatly increase its web presence, including re-writing their Flash homepage and opening an e-commerce site. If given the position, I would be the sole developer on staff.
I've been working with Rails for a number of years, and haven't looked at PHP in quite some time. However, if I was to get the job, I would be in a position to recommend the framework, as there aren't any development-savvy people already on staff.
I think for many non-programmers PHP still has huge name recognition out there as THE language for building sites, so it acts as logical default for many companies.
If I was offered this job, how could I compare the pros and cons of Rails vs PHP (with an appropriate framework) without getting into technical terminology? A key consideration here is that there are probably a lot more LAMP developers in the area than Rails developers, and I don't want my own personal preferences to impact the long-term sustainability of the code base.
Or should I just accept that a PHP/Zend site is just as good as a Rails site, even if it's less fun to develop?
(Please no religious arguments!) | I wouldn't argue that Rails is better than PHP or anything like that, because to these people they don't really care. What they do care about is:
1. that they get a good site (hence, use Rails because you're better with it), and
2. that it's not going to be a burden to maintain (hence, use PHP because it's easier to find programmers)
Just let them know these facts, and argue your point along these lines to let them decide. Also worth mentioning is that Rails is a growing community (if I believe blogs...) and the availability of developers will get better over time. | The first thing I have to say is that (imho) you're approach is wrong because you've started with a conclusion ("I want to do this in Rails") and you're now looking for a justification.
Worse, such an attitude borders on negligence as you have an ethical if not legal duty of care to your client and it's their needs you should be addressing first and foremost, not yours.
This same issue came up in [Continue a Classic ASP site or insist a language change?](https://stackoverflow.com/questions/523346/continue-a-classic-asp-site-or-insist-a-language-change)
An important point to make here is that with Rails (typically meaning Ruby on Rails although it could be Groovy, etc) you're comparing a framework to a language (PHP). There are **many** PHP frameworks so a lot of the issues of speed of coding diminish if not disappear altogether if you compare Ruby on Rails to PHP + some framework or frameworks with which you're equally familiar.
From experience I can tell you that non-technical users will be concerned with some or all of the following:
1. Cost to develop;
2. Cost to host;
3. Look and feel;
4. Site functionality;
5. Ability to find developers;
6. Stability;
7. Existing functionality; and
8. Risk.
(1) is debatable. Ruby on Rails is probably very fast if you're doing things the Ruby way but can get really difficult if requirements force you to go off the reservation. Interestingly, Microsoft stacks tend to work the same way (although they usually have a bigger reservation to further extend that metaphor).
This came up in [7 reasons I switched back to PHP after 2 years on Rails](http://www.oreillynet.com/ruby/blog/2007/09/7_reasons_i_switched_back_to_p_1.html). Agree or disagree, that sort of post makes points you'll at least need to consider and/or address.
(2) I think is a win for PHP. PHP shared hosting is extraordinarily cheap but there's not a lot in it. If the site will get a moderate amount of traffic or there are significant security concerns you'll either end up hosting it at the site or using some form of VPS or dedicated hosting at which point the issue becomes a wash.
(3) isn't really that different. Ruby is slanted twoards Prototype (being integrated) and the like whereas PHP is more open to any Javascript framework (which has advantages and disadvantages) and both can do whatever in HTML and CSS.
Same applies to (4). There's nothing you can do in one that you can't do in the other.
(5) is a clear win for PHP. You may not be hiring hundreds of developers but the fat that if you move on or are replaced that it's easy to find other people with relevant experience **is important to non-technical people** (and should be important to technical people too).
(6) is either a perceived or real win for PHP. By that I mean Ruby on Rails--at least in my experience--has a reputation for being unstable and/or wasteful of resources. This is exemplified by such postings as Zed Shaw's notorious [Rails Is A Ghetto](http://www.zedshaw.com/rants/rails_is_a_ghetto.html) rant. It clearly is a rant but there are some valid points there too.
(7) is an interesting one. Rails mandates (or rather "is") an ORM framework and like many ORM frameworks they can have real issues in dealing with "legacy" data. I put that in inverted commas because ORMs have the nasty habit of declaring anything not done their way as "legacy" (eg composite keys).
If you have complete control over the data model on this site and there's no existing data model to support then this issue is probably a win for Rails but the more constraints you have the more this will be a win for PHP's lightweight (typically raw SQL) approach.
You may want to take a look at [Using an ORM or plain SQL?](https://stackoverflow.com/questions/494816/using-an-orm-or-plain-sql)
(8) really sums up all of the above. The company will be greatly concerned with how preditable the end result is and a more predictable, less sexy end result will often win out.
The last thing I'll say is that if you have both Rails and PHP experience (as you seem to) and you need to ask what the (non-technical) merits of Rails are perhaps you need to re-examine what you're doing and why you're doing it. | Comparing Rails vs. PHP to a non-technical audience | [
"",
"php",
"ruby-on-rails",
"zend-framework",
""
] |
I have a bunch of DIVs that contain textual information. They're all the same width (maybe 400px or so), but different heights. For space reasons, I'd like to have two or three columns of these DIVs (sort of like a want-ad section in a newspaper). See attractive ascii-art below :)
```
DIV1 DIV3
DIV1 DIV3
DIV1
DIV1 DIV4
DIV1 DIV4
DIV1 DIV4
DIV4
DIV2 DIV4
DIV2
```
The DIVs are javascript-driven and change height at page-load time. I also shouldn't change their order (each DIV has a title, and they're sorted alphabetically).
So far I haven't found a good way to do it. HTML flow is left to right, then top to bottom, but I need top to bottom, then left to right.
I tried a naive implementation of a table with two columns, and have the DIVs in one column, and the other half in the other column. Have the time it looks reasonable (when the average height of the DIVs in each column comes out close), the other half it looks horrible.
I suppose if I was a javascript guru I could measure the DIVs after they've expanded, total them up, then move them from one table column to another at run time... but that's beyond my abilities, and I'm not sure it's possible anyway.
Any suggestions?
Thanks
UPDATE:
Thanks for the comments. It's obvious I did a poor job of asking the question :(
The DIVs are just a way of containing/grouping similar content -- not really using them for layout per se. They're all the same width, but different heights. I want to just spit them out on a page, and *magically* :) have them arranged into two columns, where the height of the two columns is pretty much the same -- like newspaper columns. I don't know how high the DIVs are when I start, so I don't know which column to place each DIV in (meaning that if I knew their heights, I'd split them among two table cells, but I don't know). So the example above is just a simple example -- it might turn out at run time that DIV 1 is larger than the other 3 combined (in which case DIV2 should float to the top of column2), or maybe DIV 4 turns out to be the big one (in which case DIVs 1, 2 and 3 would all be in column1, and DIV4 could be alone in column2)
Basically I was hoping there was a way to create two columns and have the content *magically* flow from column1 to column2 as needed (like Word does). I suspect this can't be done, but my HTML/CSS knowledge is pretty basic so maybe...? | The draft [CSS3 multi-column model](http://www.w3.org/TR/css3-multicol/) does what you want. Firefox seems to support [-moz versions of some of the properties](https://developer.mozilla.org/en/CSS3_Columns) and Safari/Chrome [-webkit versions](http://www.zenelements.co.uk/blog/css3-multiple-columns/); I don't know about IE8 or Opera. | You could wrap div1 and div2 in a wrapper div, and div 3 and div 4 in a wrapper div, then wrap those two in an outer wrapper. Use some css to the get formatting right and you should be good to go. The html might look something like this:
```
<div class="wrap">
<div class="col">
<div>div1</div>
<div>div2</div>
</div>
<div class="col">
<div>div3</div>
<div>div4</div>
</div>
</div>
```
Then, have some css like this:
```
.wrap {
position: relative;
overflow: auto;
}
.col {
float: left;
width: 400px;
}
```
That should do the right thing. | Implementing columns in HTML/CSS | [
"",
"javascript",
"html",
"css",
"dhtml",
""
] |
I've got a text file that looks like this:
```
{ Id = 1, ParentId = 0, Position = 0, Title = "root" }
{ Id = 2, ParentId = 1, Position = 0, Title = "child 1" }
{ Id = 3, ParentId = 1, Position = 1, Title = "child 2" }
{ Id = 4, ParentId = 1, Position = 2, Title = "child 3" }
{ Id = 5, ParentId = 4, Position = 0, Title = "grandchild 1" }
```
I'm looking for a generic C# algorithm that will create an object hierarchy from this. A "Hierarchize" function, if you will, that turns this data into an object hierarchy.
Any ideas?
*edit* I've already parsed the file into .NET objects:
```
class Node
{
public int Id { get; }
public int ParentId { get; }
public int Position { get; }
public string Title { get; }
}
```
Now I need to actually arrange the objects into an object graph. | Many thanks to Jon and to mquander - you guys gave me enough information to help me solve this in a proper, generic way. Here's my solution, a single generic extension method that converts objects into hierarchy form:
```
public static IEnumerable<Node<T>> Hierarchize<T, TKey, TOrderKey>(
this IEnumerable<T> elements,
TKey topMostKey,
Func<T, TKey> keySelector,
Func<T, TKey> parentKeySelector,
Func<T, TOrderKey> orderingKeySelector)
{
var families = elements.ToLookup(parentKeySelector);
var childrenFetcher = default(Func<TKey, IEnumerable<Node<T>>>);
childrenFetcher = parentId => families[parentId]
.OrderBy(orderingKeySelector)
.Select(x => new Node<T>(x, childrenFetcher(keySelector(x))));
return childrenFetcher(topMostKey);
}
```
Utilizes this small node class:
```
public class Node<T>
{
public T Value { get; private set; }
public IList<Node<T>> Children { get; private set; }
public Node(T value, IEnumerable<Node<T>> children)
{
this.Value = value;
this.Children = new List<Node<T>>(children);
}
}
```
It's generic enough to work for a variety of problems, including my text file issue. Nifty!
\*\*\*\*UPDATE\*\*\*\*: Here's how you'd use it:
```
// Given some example data:
var items = new[]
{
new Foo()
{
Id = 1,
ParentId = -1, // Indicates no parent
Position = 0
},
new Foo()
{
Id = 2,
ParentId = 1,
Position = 0
},
new Foo()
{
Id = 3,
ParentId = 1,
Position = 1
}
};
// Turn it into a hierarchy!
// We'll get back a list of Node<T> containing the root nodes.
// Each node will have a list of child nodes.
var hierarchy = items.Hierarchize(
-1, // The "root level" key. We're using -1 to indicate root level.
f => f.Id, // The ID property on your object
f => f.ParentId, // The property on your object that points to its parent
f => f.Position, // The property on your object that specifies the order within its parent
);
``` | Hmm... I don't quite see how that works. How can 2 and 5 both have parent=1, position=0? Should 5 have parent 2, 3 or 4?
Okay, this new version goes through the all the nodes three times:
* Load all nodes and put them into the a map
* Associate each node with its parent
* Sort each node's child by position
It's not well-encapsulated, nicely error checking etc - but it works.
```
using System;
using System.Collections.Generic;
using System.IO;
public class Node
{
private static readonly char[] Braces = "{}".ToCharArray();
private static readonly char[] StringTrim = "\" ".ToCharArray();
public Node Parent { get; set; }
public int ParentId { get; private set; }
public int Id { get; private set; }
public string Title { get; private set; }
public int Position { get; private set; }
private readonly List<Node> children = new List<Node>();
public List<Node> Children { get { return children; } }
public static Node FromLine(string line)
{
Node node = new Node();
line = line.Trim(Braces);
string[] bits = line.Split(',');
foreach (string bit in bits)
{
string[] keyValue = bit.Split('=');
string key = keyValue[0].Trim();
string value = keyValue[1].Trim();
switch (key)
{
case "Id":
node.Id = int.Parse(value);
break;
case "ParentId":
node.ParentId = int.Parse(value);
break;
case "Position":
node.Position = int.Parse(value);
break;
case "Title":
node.Title = value.Trim(StringTrim);
break;
default:
throw new ArgumentException("Bad line: " + line);
}
}
return node;
}
public void Dump()
{
int depth = 0;
Node node = this;
while (node.Parent != null)
{
depth++;
node = node.Parent;
}
Console.WriteLine(new string(' ', depth * 2) + Title);
foreach (Node child in Children)
{
child.Dump();
}
}
}
class Test
{
static void Main(string[] args)
{
var dictionary = new Dictionary<int, Node>();
using (TextReader reader = File.OpenText("test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Node node = Node.FromLine(line);
dictionary[node.Id] = node;
}
}
foreach (Node node in dictionary.Values)
{
if (node.ParentId != 0)
{
node.Parent = dictionary[node.ParentId];
node.Parent.Children.Add(node);
}
}
foreach (Node node in dictionary.Values)
{
node.Children.Sort((n1, n2) =>
n1.Position.CompareTo(n2.Position));
}
Node root = dictionary[1];
root.Dump();
}
}
```
Sample text file:
```
{ Id = 5, ParentId = 4, Position = 0, Title = "grandchild 1" }
{ Id = 2, ParentId = 1, Position = 0, Title = "child 1" }
{ Id = 4, ParentId = 1, Position = 2, Title = "child 3" }
{ Id = 3, ParentId = 1, Position = 1, Title = "child 2" }
{ Id = 1, ParentId = 0, Position = 0, Title = "root" }
```
Output:
```
root
child 1
child 2
child 3
grandchild 1
``` | C# algorithm for generating hierarchy | [
"",
"c#",
"algorithm",
"hierarchy",
"hierarchical-data",
""
] |
How do I create a foreign key
from table tGeoAnswers column 'locationId'
to table tLocations column 'id'?
```
ALTER TABLE
tGeoAnswers
ADD
FK_Answer_Location
FOREIGN KEY
(locationId)
REFERENCES
tLocations(id)
```
I am trying this code that I found but I get the following error:
The definition for column 'FK\_Answer\_Location' must include a data type | ```
ALTER TABLE tGeoAnswers ADD CONSTRAINT FK_Answer_Location ...
```
Otherwise it assumes you're adding a column called `FK_Answer_Location`. | Assuming MsSql Server/T-SQL, use [ALTER TABLE](http://msdn.microsoft.com/en-us/library/ms190273.aspx):
```
ALTER TABLE tGeoAnswers
ADD CONSTRAINT FK_Answer_Location
FOREIGN KEY (LocationId) REFERENCES tLocation (Id)
``` | Create Foreign Key SQL | [
"",
"sql",
"sql-server",
"foreign-keys",
""
] |
Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.
For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...
How can I do that (preferably in Python)?
Thanks! :) | You can generate all the subsets using a [Branch-and-bound](http://en.wikipedia.org/wiki/Branch_and_bound) technique: you can generate all the subsets in an incremental fashion (generating superset of subsets already determined), using as a prune condition "does not explore this branch of the tree if the root does not satify the constraint".
If you want to be generic regarding the constraint, I think this is the best strategy.
Be sure to write in a correct manner the code that generates the subsets, otherwise you generate many time the same subsets: in order to avoid memoization, which can be time-consuming due to map lookups and introduce memory overhead, you can generate the subsets in that manner:
```
GetAllSubsets(List objects) {
List generated = {};
GetAllSubsets(generated, [], objects);
return generated;
}
GetAllSubsets(List subsetGenerated, List objectFixed, List objectsToFix) {
GetAllSubsets(subsetGenerated, objectFixed, objectsToFix.sublist(1, objectsToFix.length());
if (satisfy(toCheck = objectsFixed.add(objectsToFix.get(0)))) {
subsetGenerated.add(toCheck);
GetAllSubsets(subsetGenerated, toCheck, objectsToFix.sublist(1, objectsToFix.length());
}
}
```
In fact, the subsets added by the first invocation of GetAllSubsets doesn't have the first element of objectsToFix, where the subsets added by the second call (if the pruning condition isn't violated) have that element, so the intersection of the two sets of subsets generated is empty. | You could construct your sets recursively, starting with the empty set and attempting to add more elements, giving up on a recursive line of execution if one of the subsets (and thus all of its supersets) fails to meet the condition. Here's some pseudocode, assuming a set S whose condition-satisfying subsets you would like to list. For convenience, assume that the elements of S can be indexed as x(0), x(1), x(2), ...
```
EnumerateQualifyingSets(Set T)
{
foreach (x in S with an index larger than the index of any element in T)
{
U = T union {x}
if (U satisfies condition)
{
print U
EnumerateQualifyingSets(U)
}
}
}
```
The first call would be with T as the empty set. Then, all the subsets of S matching the condition would be printed. This strategy relies crucially on the fact that a subset of S which does not meet the condition cannot be contained in one that does. | An algorithm to generate subsets of a set satisfying certian conditions | [
"",
"python",
"algorithm",
"subset",
""
] |
I am performing two parallel requests to my web service using WebClient and multithreading them with ThreadPool. However, I'm having an issue in one of the threads where I get this WebException:
> The server committed a protocol violation. Section=ResponseStatusLine
I did some research and found that it could be an unsafe header validation issue, but the requests work fine in single thread mode.
So just to clarify, I am firing off two threads. One is doing a GET of a URI, and one is doing a POST of some data to a URI. The first GET works fine, but the POST fails with the WebException above.
Any ideas?
Thanks. | I fixed my issue by adding
```
request.ServicePoint.Expect100Continue = false;
```
before making my POST call. What was happening according to wireshark was my HttpWebRequest was expecting 100 continue, but getting 401 not authorized, but it was sending the data anyways after the server response, instead of sending an authorization header. It wasn't happening everytime, but this seems to fix it. | Adding following to web.config solved my problem.
```
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
``` | WebClient multi-threaded response | [
"",
"c#",
"httpwebrequest",
""
] |
I'm trying to compile [this example](http://boost-sandbox.sourceforge.net/libs/accumulators/doc/html/accumulators/user_s_guide/the_statistical_accumulators_library.html#accumulators.user_s_guide.the_statistical_accumulators_library.weighted_p_square_cumulative_distribution)
But that one header isn't enough and I've already spent half an hour trying to clobber all of the errors. Why aren't the required includes specified?
I did this:
```
#include <boost/accumulators/statistics/weighted_p_square_cumulative_distribution.hpp>
#include <vector>
#include <boost/accumulators/accumulators.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/random/lagged_fibonacci.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/fusion/support/void.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
using namespace boost::accumulators;
using namespace boost;
int main() {
// tolerance in %
double epsilon = 4;
typedef accumulator_set<double, stats<tag::weighted_p_square_cumulative_distribution>, double > accumulator_t;
accumulator_t acc_upper(tag::weighted_p_square_cumulative_distribution::num_cells = 100);
accumulator_t acc_lower(tag::weighted_p_square_cumulative_distribution::num_cells = 100);
// two random number generators
double mu_upper = 1.0;
double mu_lower = -1.0;
boost::lagged_fibonacci607 rng;
boost::normal_distribution<> mean_sigma_upper(mu_upper,1);
boost::normal_distribution<> mean_sigma_lower(mu_lower,1);
boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal_upper(rng, mean_sigma_upper);
boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal_lower(rng, mean_sigma_lower);
for (std::size_t i=0; i<100000; ++i)
{
double sample = normal_upper();
acc_upper(sample, weight = std::exp(-mu_upper * (sample - 0.5 * mu_upper)));
}
for (std::size_t i=0; i<100000; ++i)
{
double sample = normal_lower();
acc_lower(sample, weight = std::exp(-mu_lower * (sample - 0.5 * mu_lower)));
}
typedef iterator_range<std::vector<std::pair<double, double> >::iterator > histogram_type;
histogram_type histogram_upper = weighted_p_square_cumulative_distribution(acc_upper);
histogram_type histogram_lower = weighted_p_square_cumulative_distribution(acc_lower);
// Note that applaying importance sampling results in a region of the distribution
// to be estimated more accurately and another region to be estimated less accurately
// than without importance sampling, i.e., with unweighted samples
for (std::size_t i = 0; i < histogram_upper.size(); ++i)
{
// problem with small results: epsilon is relative (in percent), not absolute!
// check upper region of distribution
if ( histogram_upper[i].second > 0.1 )
BOOST_CHECK_CLOSE( 0.5 * (1.0 + erf( histogram_upper[i].first / sqrt(2.0) )), histogram_upper[i].second, epsilon );
// check lower region of distribution
if ( histogram_lower[i].second < -0.1 )
BOOST_CHECK_CLOSE( 0.5 * (1.0 + erf( histogram_lower[i].first / sqrt(2.0) )), histogram_lower[i].second, epsilon );
}
}
```
And I got these errors:
```
In file included from /opt/local/include/boost/accumulators/statistics/weighted_p_square_cumulative_distribution.hpp:17,
from a.cc:1:
/opt/local/include/boost/accumulators/framework/extractor.hpp: In instantiation of 'boost::accumulators::detail::accumulator_set_result<boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::weighted_p_square_cumulative_distribution, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, double>, boost::accumulators::tag::weighted_p_square_cumulative_distribution>':
/opt/local/include/boost/mpl/eval_if.hpp:38: instantiated from 'boost::mpl::eval_if<boost::accumulators::detail::is_accumulator_set<boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::weighted_p_square_cumulative_distribution, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, double> >, boost::accumulators::detail::accumulator_set_result<boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::weighted_p_square_cumulative_distribution, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, double>, boost::accumulators::tag::weighted_p_square_cumulative_distribution>, boost::accumulators::detail::argument_pack_result<boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::weighted_p_square_cumulative_distribution, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, double>, boost::accumulators::tag::weighted_p_square_cumulative_distribution> >'
/opt/local/include/boost/accumulators/framework/extractor.hpp:57: instantiated from 'boost::accumulators::detail::extractor_result<boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::weighted_p_square_cumulative_distribution, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na, mpl_::na>, double>, boost::accumulators::tag::weighted_p_square_cumulative_distribution>'
a.cc:47: instantiated from here
/opt/local/include/boost/accumulators/framework/extractor.hpp:36: error: no type named 'result_type' in 'struct boost::fusion::void_'
a.cc: In function 'int main()':
a.cc:47: error: no match for call to '(const boost::accumulators::extractor<boost::accumulators::tag::weighted_p_square_cumulative_distribution>) (main()::accumulator_t&)'
a.cc:48: error: no match for call to '(const boost::accumulators::extractor<boost::accumulators::tag::weighted_p_square_cumulative_distribution>) (main()::accumulator_t&)'
``` | The examples shown in the docs are extracted from the library's unit tests. Take a look at `libs/accumulators/test/weighted_p_square_cum_dist.cpp` | Just ran into this problem. The solution for me was
#include <boost/accumulators/statistics/stats.hpp> | What are the right includes for using the boost accumulators library? | [
"",
"c++",
""
] |
I am in need of a piece of code that can detect if a network connection is connected or disconnected. The connected state would mean a cable was plugged into the Ethernet connection. A disconnected state would mean there is not cable connected.
I can't use the WMI interface due to the fact that I'm running on Windows CE. I don't mind invoking the Win32 API but remember that I'm using Windows CE and running on the Compact Framework. | Check out this MSDN article:
[Testing for and Responding to Network Connections in the .NET Compact Framework](http://msdn.microsoft.com/en-us/library/aa446548.aspx) | The easiest way is to use [OpenNETCF's SDF](http://opennetcf.codeplex.com) and look at the [OpenNETCF.Net.NetworkInformation.NetworkInterfaceWatcher class](http://opennetcf.codeplex.com/SourceControl/latest#OpenNETCF.Net/OpenNETCF.Net/NetworkInformation/NetworkInterfaceWatcher.cs), which will raise events when NDIS sends out notifications (like MEDIA\_CONNECT and MEDIA\_DISCONNECT).
You can do the same work without the SDF, of course. It involves onening the NDIS driver directly and calling [IOCTL\_NDISUIO\_REQUEST\_NOTIFICATION](http://msdn.microsoft.com/en-us/library/aa924905.aspx) with a P2P message queue handle. It's not overly difficult, but there's a lot you have to get right for it to work and not leak. | Detecting network state (connected - disconnected) in C# | [
"",
"c#",
"compact-framework",
"networking",
"windows-ce",
"ethernet",
""
] |
I am playing around with the boost strings library and have just come across the awesome simplicity of the split method.
```
string delimiters = ",";
string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
// If we didn't care about delimiter characters within a quoted section we could us
vector<string> tokens;
boost::split(tokens, str, boost::is_any_of(delimiters));
// gives the wrong result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters", " inside a quote\""}
```
Which would be nice and concise... however it doesn't seem to work with quotes and instead I have to do something like the following
```
string delimiters = ",";
string str = "string, with, comma, delimited, tokens, \"and delimiters, inside a quote\"";
vector<string> tokens;
escaped_list_separator<char> separator("\\",delimiters, "\"");
typedef tokenizer<escaped_list_separator<char> > Tokeniser;
Tokeniser t(str, separator);
for (Tokeniser::iterator it = t.begin(); it != t.end(); ++it)
tokens.push_back(*it);
// gives the correct result: tokens = {"string", " with", " comma", " delimited", " tokens", "\"and delimiters, inside a quote\""}
```
My question is can split or another standard algorithm be used when you have quoted delimiters? Thanks to purpledog but I already have a non-deprecated way of achieving the desired outcome, I just think that it's quite cumbersome and unless I could replace it with a simpler more elegant solution I wouldn't use it in general without first wrapping it in yet another method.
EDIT: Updated code to show results and clarify question. | It doesn't seem that there is any simple way to do this using the boost::split method. The shortest piece of code I can find to do this is
```
vector<string> tokens;
tokenizer<escaped_list_separator<char> > t(str, escaped_list_separator<char>("\\", ",", "\""));
BOOST_FOREACH(string s, escTokeniser)
tokens.push_back(s);
```
which is only marginally more verbose than the original snippet
```
vector<string> tokens;
boost::split(tokens, str, boost::is_any_of(","));
``` | This will achieve the same result as Jamie Cook's answer without the explicit loop.
```
tokenizer<escaped_list_separator<char> >tok(str);
vector<string> tokens( tok.begin(), tok.end() );
```
The tokenizer constructor's second parameter defaults to `escaped_list_separator<char>("\\", ",", "\"")` so it's not necessary. Unless you have differing requirements for commas or quotes. | Using escaped_list_separator with boost split | [
"",
"c++",
"boost",
"split",
"tokenize",
""
] |
What's the best way to pass arguments to a tomcat instance? Are command line arguments available to all applications within the container? Can I pass arguments to particular apps? Do I need to manage this through the built in app server?
**EDIT:**
To clarify, I'm looking to pass a parameter to specify the configs to use. Sometimes this might specify a set of configuration files which can differ per environment. | I believe that the best way to configure it would be to use the server.xml and context.xml files. This is the place to add JNDI configuration. You can have a different context.xml file for every application. In your WAR file place this at META-INF directory and Tomcat will import it. | you can add -Dmy.config.var=configA and -Dmy.config.var=configB and to CATALINA\_OPTS (each time the one you need) and read them from java via System.getProperty("my.config.var"). These are not environment variables. | What's the best way to pass arguments to a tomcat instance? | [
"",
"java",
"tomcat",
"jakarta-ee",
""
] |
First, here is what I would like to do:
```
Row 1
Row 2
Row 3
```
I have code setup so that when I hover over row1, 2 or 3, the row gets highlighted. This is done via css.
I would like to be able to (for instance) click row1 and then it would look like this:
```
Row 1
Some text here
Row 2
Row 3
```
That text would stay there until I clicked on a different row at which point it would go away. For instance, let's say I clicked on row 2 next.
```
Row 1
Row 2
Even more text here
Row 3
```
I have found code that talks about using javascript to do this and setting the visibility of the text but I'm not sure how I can do this without having a ton of near duplicate code... | If you have more javascript than the needed for this feature jQuery is justified and it will come handy. With jQuery, it would be something like
```
$(".classOfYourRows").
click(function(){
$(".classOfChildren").hide();
$(".classOfChildren", this).show();
});
``` | CSS:
```
.outer {
display: block;
}
.outer .inner {
display: none;
margin-left: 10px;
}
.outer:hover {
background-color: #EEEEEE;
}
.outer:active .inner {
display: block;
}
```
HTML:
```
<div class="outer">
Row 1
<div class="inner">some text</div>
</div>
<div class="outer">
Row 2
<div class="inner">some text</div>
</div>
<div class="outer">
Row 3
<div class="inner">some text</div>
</div>
```
I think that's as close as you can get without using Javascript.
Edit: I think I may have misread the question, I thought he didn't want to use Javascript. Oh well, I'll leave my answer up anyway. | Is there a cross browser way to expand text on click via css? | [
"",
"javascript",
"css",
"hover",
"highlight",
"expand",
""
] |
I have a question about events in .NET (C#). I have had to write code for several situations in which I have a background task running and I want to notify a main thread, or controller class, that something has occurred, such as task completed, or finished copying a file, but I don't want the background task to wait for the main thread's delegate to process the event.
I want to do something like message passing: Send the message, but who cares what they do with it.
**For example:**
A class is written to process several processes in sequence, one after the other. Each process needs to run on a background thread. When work is completed, an event fires and tells the controller that it's done (let's say using OnCompleted() method)
The problem is that if the controller's event handler is used to start the subsequent process, the previous processes' OnComplete method stays on the call stack (never finishes executing) until the all of the processes have completed.
In that situation, how could the background task notify the controller class that the work is done without keeping the event raising method on the stack?
**Example 2:** A backup program.
A background thread runs to copy each file to the destination. The background needs to *notify* the UI the last file that was copied, but it doesn't need to wait for the UI to update. Instead, it just wants to say, "BTW, here's some info. Now, let me get back to work." The event listener shouldn't block the processing of the event raiser. | You could do an async invoke when raising the event (as mentioned), or just raise the event itself on a background thread:
```
void OnUpdated(EventArgs e) {
EventHandler h = this.Updated;
if (h != null) h(e);
}
void DoStuff() {
BigMethod();
ThreadPool.QueueUserWorkItem(OnUpdated, EventArgs.Empty);
BigMethod2();
}
```
If you raise asynchronously, multiple listeners would be processing your event at the same time. At the very least, that requires a thread-safe EventArg class. If you expect them to interact with your class as well, then you should document very carefully or make it thread-safe as well.
Raising the event on a background thread carries the same caveats for your class methods, but you don't have to worry about the EventArgs class itself. | It sounds like you are trying to invoke the delegates in the event's invocation list asynchronously.
I would suggest that you read [.NET Asynchronous Events To Send Process Status To User Interface](http://www.eggheadcafe.com/articles/asynchronous_events.asp):
> The .NET Framework offers us the
> concept of raising events (and other
> items) in our classes asynchronously.
> This means that we can raise the event
> in such a way as to not have the
> subscriber to that event (typically
> the user interface) hold up the
> processing in the method that raised
> the event. The benefit being that it
> doesn't negatively impact the
> performance of our business layer
> method. | How can I fire an event without waiting for the event listeners to run? | [
"",
"c#",
"events",
"message",
""
] |
I'm just starting out with WPF and need some help with routed events. I have added a datagrid with some animation, but i can't seem to find anywhere that shows me a list of routed events to use on the datagrid, or any other control for that matter. Seems to be a guessing game so far.
I thought the datagrid standard events, such as CellEditEnding, was it but they are not as it says "Invalid event name".
The example I copied used a MouseEnter routed event, but i don't know what else there is for me to use (except my own of course).
```
<Window.Triggers>
<EventTrigger RoutedEvent="my:DataGrid.MouseEnter">
<BeginStoryboard Storyboard="{StaticResource MyAnimation}"/>
</EventTrigger>
</Window.Triggers>
```
thanks in advance for you help | In your code, call static EventManager.GetRoutedEvents() method to get list of routed events registered/available to your application. | Here's the list...
```
[0]: {FrameworkElement.RequestBringIntoView}
[1]: {FrameworkElement.SizeChanged}
[2]: {FrameworkElement.Loaded}
[3]: {FrameworkElement.Unloaded}
[4]: {ToolTipService.ToolTipOpening}
[5]: {ToolTipService.ToolTipClosing}
[6]: {ContextMenuService.ContextMenuOpening}
[7]: {ContextMenuService.ContextMenuClosing}
[8]: {Mouse.PreviewMouseDown}
[9]: {Mouse.MouseDown}
[10]: {Mouse.PreviewMouseUp}
[11]: {Mouse.MouseUp}
[12]: {UIElement.PreviewMouseLeftButtonDown}
[13]: {UIElement.MouseLeftButtonDown}
[14]: {UIElement.PreviewMouseLeftButtonUp}
[15]: {UIElement.MouseLeftButtonUp}
[16]: {UIElement.PreviewMouseRightButtonDown}
[17]: {UIElement.MouseRightButtonDown}
[18]: {UIElement.PreviewMouseRightButtonUp}
[19]: {UIElement.MouseRightButtonUp}
[20]: {Mouse.PreviewMouseMove}
[21]: {Mouse.MouseMove}
[22]: {Mouse.PreviewMouseWheel}
[23]: {Mouse.MouseWheel}
[24]: {Mouse.MouseEnter}
[25]: {Mouse.MouseLeave}
[26]: {Mouse.GotMouseCapture}
[27]: {Mouse.LostMouseCapture}
[28]: {Mouse.QueryCursor}
[29]: {Stylus.PreviewStylusDown}
[30]: {Stylus.StylusDown}
[31]: {Stylus.PreviewStylusUp}
[32]: {Stylus.StylusUp}
[33]: {Stylus.PreviewStylusMove}
[34]: {Stylus.StylusMove}
[35]: {Stylus.PreviewStylusInAirMove}
[36]: {Stylus.StylusInAirMove}
[37]: {Stylus.StylusEnter}
[38]: {Stylus.StylusLeave}
[39]: {Stylus.PreviewStylusInRange}
[40]: {Stylus.StylusInRange}
[41]: {Stylus.PreviewStylusOutOfRange}
[42]: {Stylus.StylusOutOfRange}
[43]: {Stylus.PreviewStylusSystemGesture}
[44]: {Stylus.StylusSystemGesture}
[45]: {Stylus.GotStylusCapture}
[46]: {Stylus.LostStylusCapture}
[47]: {Stylus.StylusButtonDown}
[48]: {Stylus.StylusButtonUp}
[49]: {Stylus.PreviewStylusButtonDown}
[50]: {Stylus.PreviewStylusButtonUp}
[51]: {Keyboard.PreviewKeyDown}
[52]: {Keyboard.KeyDown}
[53]: {Keyboard.PreviewKeyUp}
[54]: {Keyboard.KeyUp}
[55]: {Keyboard.PreviewGotKeyboardFocus}
[56]: {Keyboard.GotKeyboardFocus}
[57]: {Keyboard.PreviewLostKeyboardFocus}
[58]: {Keyboard.LostKeyboardFocus}
[59]: {TextCompositionManager.PreviewTextInput}
[60]: {TextCompositionManager.TextInput}
[61]: {DragDrop.PreviewQueryContinueDrag}
[62]: {DragDrop.QueryContinueDrag}
[63]: {DragDrop.PreviewGiveFeedback}
[64]: {DragDrop.GiveFeedback}
[65]: {DragDrop.PreviewDragEnter}
[66]: {DragDrop.DragEnter}
[67]: {DragDrop.PreviewDragOver}
[68]: {DragDrop.DragOver}
[69]: {DragDrop.PreviewDragLeave}
[70]: {DragDrop.DragLeave}
[71]: {DragDrop.PreviewDrop}
[72]: {DragDrop.Drop}
[73]: {Touch.PreviewTouchDown}
[74]: {Touch.TouchDown}
[75]: {Touch.PreviewTouchMove}
[76]: {Touch.TouchMove}
[77]: {Touch.PreviewTouchUp}
[78]: {Touch.TouchUp}
[79]: {Touch.GotTouchCapture}
[80]: {Touch.LostTouchCapture}
[81]: {Touch.TouchEnter}
[82]: {Touch.TouchLeave}
[83]: {FocusManager.GotFocus}
[84]: {FocusManager.LostFocus}
[85]: {ManipulationDevice.ManipulationStarting}
[86]: {ManipulationDevice.ManipulationStarted}
[87]: {ManipulationDevice.ManipulationDelta}
[88]: {ManipulationDevice.ManipulationInertiaStarting}
[89]: {ManipulationDevice.ManipulationBoundaryFeedback}
[90]: {ManipulationDevice.ManipulationCompleted}
[91]: {Control.PreviewMouseDoubleClick}
[92]: {Control.MouseDoubleClick}
[93]: {ScrollViewer.ScrollChanged}
[94]: {ScrollBar.Scroll}
[95]: {Thumb.DragStarted}
[96]: {Thumb.DragDelta}
[97]: {Thumb.DragCompleted}
[98]: {RangeBase.ValueChanged}
[99]: {TextBoxBase.TextChanged}
``` | How can I get a list of built-in routed events in WPF | [
"",
"c#",
".net",
"wpf",
"events",
"xaml",
""
] |
Is it possible to inherit from the Thread class and override the Start method? | I don't think any inheritance could result in a more readable code than this:
```
Thread myThread = new Thread(() =>
{
//Do what you want...
});
myThread.Start();
``` | Regarding why someone would want to do this: a lot of languages (e.g. Java) and/or thread APIs (e.g. Qt) allow developers to implement threads by inheriting from a "thread" base class, and then overloading a method that implements the thread routine.
Having used this model extensively in Qt, I actually find it very handy--instead of having threads target some function or method, which often leads to weird and/or convoluted code, the whole thread is contained inside of an object.
Here's example code using the Qt API:
```
class MyThread : public QThread
{
Q_OBJECT
protected:
void run();
};
void MyThread::run()
{
...something I need threaded...
}
```
QThread is Qt's threading base class. To use MyThread, create an instance of the thread object and call QThread::start(). The code that appears in the run() reimplementation will then be executed in a separate thread.
What's nice about this is I think it lets you really contain everything a thread needs inside a single object, and (in my experience), it makes for a very coherent object model. I don't think it meets everyone's needs, but I was a bit surprised that C# doesn't have such a basic threading model to be honest.
I definitely don't buy that C#'s Thread class is sealed because of kernel complexity; if Qt can supply a cross-platform threading library that allows inheritance of QThread, I see no real reason MSFT couldn't provide the same capability in a threading class in C#. | System.Threading.Thread inheritance | [
"",
"c#",
"multithreading",
""
] |
I recently discovered that `x**.5` and `math.sqrt(x)` do not always produce the same result in Python:
```
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
```
Checking all integers below 10\*\*7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.
So the question is, which method is more accurate? | Neither one is more accurate, they both diverge from the actual answer in equal parts:
```
>>> (8885558**0.5)**2
8885557.9999999981
>>> sqrt(8885558)**2
8885558.0000000019
>>> 2**1023.99999999999
1.7976931348498497e+308
>>> (sqrt(2**1023.99999999999))**2
1.7976931348498495e+308
>>> ((2**1023.99999999999)**0.5)**2
1.7976931348498499e+308
>>> ((2**1023.99999999999)**0.5)**2 - 2**1023.99999999999
1.9958403095347198e+292
>>> (sqrt(2**1023.99999999999))**2 - 2**1023.99999999999
-1.9958403095347198e+292
```
<http://mail.python.org/pipermail/python-list/2003-November/238546.html>
> The math module wraps the platform C
> library math functions of the same
> names; `math.pow()` is most useful if
> you need (or just want) high
> compatibility with C extensions
> calling C's `pow()`.
>
> `__builtin__.pow()` is the implementation of Python's infix `**`
> operator, and deals with complex
> numbers, unbounded integer powers, and
> modular exponentiation too (the C
> `pow()` doesn't handle any of those).
\*\* is more complete. `math.sqrt` is probably just the C implementation of sqrt which is probably related to `pow`. | Both the `pow` function and the `math.sqrt()` function can calculate results that are more accurate than what the default float type can store. I think the errors you're seeing is a result of the limitations of floating point math rather than inaccuracies of the functions. Also, since when is a difference of ~10^(-13) a problem when taking the square root of a 7 digit number? Even the most accurate physics calculations seldom requires that many significant digits...
Another reason to use `math.sqrt()` is that it's easier to read and understand, which generally is a good reason to do things a certain way. | Which is more accurate, x**.5 or math.sqrt(x)? | [
"",
"python",
"floating-point",
""
] |
I'm developing a Firefox addon that needs to interact with an external WebService
The WebSerivce is build using ASP.NET (.asmx page)
I cannot use ajax because it's an addon and not a web site.
Does anyone knows how to do it? | Check out this link: It clearly mentions that XMLHttpRequest can be used from Mozilla extensions. <https://developer.mozilla.org/En/Using_XMLHttpRequest#Downloading_JSON.c2.a0and_JavaScript_from_extensions> | If you would like to do it all manually you need to use the [XMLHttp Object](http://www.w3.org/TR/XMLHttpRequest/).
This however can become quite painfull, and that is the reason why there is a lot of Javascript libaries, to make the task of getting and sending data less painful. | Calling a WebService from javascript | [
"",
"javascript",
"web-services",
"firefox-addon",
""
] |
This is some code to unblock any website from listview, but now I want to unblock a website which has previously been blocked. How can I do this?
```
String path = @"C:\Windows\System32\drivers\etc\hosts";
StreamWriter sw = new StreamWriter(path, true);
String sitetoblock = "\n 127.0.0.1 http://"+listView1.SelectedItems[0].Text+"";
sw.Write(sitetoblock);
sw.Close();
MessageBox.Show(listView1.SelectedItems[0].Text " blocked");
``` | It's not the right way to block a website, but here is the way to 'unblock' a site that is 'blocked' by your code is simply :
1. read the host file
2. find the site url by regex
3. delete the line
4. save the file. | You can use `System.IO.File`'s `ReadAllLines` & `WriteAllLines` functions
and just strip out the line you want to remove
```
string path = @"C:\Windows\System32\drivers\etc\hosts";
string [] lineArray = System.IO.File.ReadAllLines(path);
List<string> lines = blah.ToList();
string sitetoUNblock = string.Format("127.0.0.1 http://{0}", listView1.SelectedItems[0].Text);
lines.Remove(sitetoUNblock);
System.IO.File.WriteAllLines(path, lines.ToArray());
``` | How to unblock website which is blocked, using C#? | [
"",
"c#",
"file-io",
"hosts",
""
] |
I'm debugging an old Infragistic grid. One of the javascript functions executes more times than needed. It was coded to be executed when a user clicks a cell in the grid. However, sometimes it runs when on mouse is over the cell. I'd like to know if there's a way to track what event caused this function to run.
Multiple executions of that function happens only in FireFox, IE behaves as it intended. | Firebug has a really helpful debugger : <http://getfirebug.com/js.html>
There is a nice tutorial [here](http://thecodecentral.com/2007/08/01/debug-javascript-with-firebug) that will tell you all what you need to know. | The most awesome css, javascript, html, dom, everything-else extension: [Firebug](http://getfirebug.com/index.html). | How to find out what event cause a javascript function to be executed in FireFox? | [
"",
"javascript",
"firefox",
""
] |
I have tried wcscat() but i get a runtime access violation.
```
wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t* c;
c = wcscat(a, b);
```
Can somebody tell me what is wrong here? Or another way to solve my problem? Thanks | `wcscat` doesn't create a new string - it simply appends `b` to `a`. So, if you want to make sure you don't cause a runtime access violation, you need to make sure there's space for `b` at the end of `a`. In the case above:
```
wchar_t a[7] = L"aaa";
wchar_t b[] = L"bbb";
wchar_t* c;
c = wcscat(a, b);
```
You can still get a return value from the function, but it will simply return `a`. | Use c++'s built in wstring:
```
#include <string>
using std::wstring;
int main()
{
wstring a = L"aaa";
wstring b = L"bbb";
wstring c = a + b;
}
```
`wcscat` is for c-style strings, not c++ style strings. The c way to do this is
```
wchar_t* a = L"aaa";
wchar_t* b = L"bbb";
wchar_t c[7];
wcscpy(c, a);
wcscat(c, b);
```
EDIT: Wow, now that I edited it, it makes it look like I copied one of the answers below. | Need help appending one wchar_t to another! C++ | [
"",
"c++",
""
] |
When making the case for library usage within an application, what arguments lead to the greatest success? How have you successfully helped co-workers see the benefits of library usage?
Specifically in the context where:
1. The library is open source.
2. The library is for JavaScript, HTML, CSS.
3. A team of developers has a culture where they believe they have seen it all, think they can program it all, and are generally suspicious of things outside their comfort zone (what they understand and have skill in).
4. The development team has kludged together 10+ years of this infrastructure type of code.
5. This homegrown code is embedded in server-side code.
6. The team does not use a web-development IDE.
7. The target user audience is currently 99.9% IE 6.0. | You know, the best arguments I come up with for this are that no matter how good your team is, bugs are inevitable; with an open source library, somebody has already found the bugs and fixed them. That's by far the most persuasive argument I've used in that precise sort of situation. No matter how self-confident your developers are, they have to admit that even they have bugs in their code occasionally, and using code that's already been extensively tested and debugged removes much of that indeterminacy. | If you're planning on doing anything interesting with javascript, and your team doesn't think they need a javascript library, then they're definitely inexperienced in that arena.
They're obviously unaware of the hell that is browser incompatibility issues, especially with respect to IE6.
When you're working in the browser, you're not working with one platform, you're working with 4 quirky, incompatible platforms. | What are persuasive arguments for making the library case? | [
"",
"javascript",
"open-source",
""
] |
I'm stumped, I can't seem to get this simple Javascript function to get called.
Thanks!
```
<html>
<head>
<script type="text/javascript">
function increase()
{
alert(" the button was pressed");
}
</script>
</head>
<body>
<form action="Test.html" method="post">
<input type="submit" onclick="increase();" />
</form>
</body>
</html>
``` | It is hard to tell where you are going wrong. It looks like you are just defining a function. This will case the increase function to run when the page is loaded:
```
<script type="text/javascript">
function increase() {
alert(" the button was pressed");
}
increase();
</script>
```
This will run the function when a button is pressed.
```
<script type="text/javascript">
function increase() {
alert(" the button was pressed");
}
</script>
<button onclick="increase()">text</button>
```
It sounds like you are just getting started, and that is awesome. I would also suggest getting a book. A few years ago, I read [DOM Scripting](http://domscripting.com/book/) by Jeremy Keith, it was okay. Also, try looking around online for tutorials. | Try this:
```
<input type="button" id="buttonId">Button</input>
<script language="javascript">
function increase() { alert(" the button was pressed"); }
document.getElementById("buttonId").onClick=increase;
</script>
``` | Function call in JavaScript | [
"",
"javascript",
"function",
"call",
""
] |
How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object? | Many different date formats can be converted to date objects just by passing them to the `Date()` constructor:
```
var date = new Date(datestring);
```
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
```
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
```
If the date formats you're receiving are consistent, you can fix them up this way:
```
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
``` | I'd use the Datejs library's parse method.
<http://www.datejs.com/>
I tried your example and it worked fine...
**5/27 11:00pm**
**Wednesday, May 27, 2009 11:00:00 PM** | Javascript convert "05/27 11:00pm" to date? | [
"",
"javascript",
""
] |
I just received some really great help today with a prior jQuery problem and figured since my luck was running that maybe I could also get some help with some checkboxes. Can someone please tell me what I am doing wrong?
Thanks!
The checkboxes are correctly echoing the database bool values but when I submit the changed values, an alert() telles me that they are undefined.
```
else if (item.field == "admCustRptDly" && item.value == "1")
{
$('#admCustRptDly').attr('checked', true);
}
else if (item.field == "admCustRptSumm" && item.value == "1")
{
$('#admCustRptSumm').attr('checked', true);
}
else if (item.field == "admCustRptDtl" && item.value == "1")
{
$('#admCustRptDtl').attr('checked', true);
}
<tr>
<td class="admMarker">Daily<input type="checkbox" id="admCustRptDly" name="admCustRptDly" class="admChkbx"></td>
<td class="admMarker">Summary<input type="checkbox" id="admCustRptSumm" name="admCustRptSumm" class="admChkbx"></td>
<td class="admMarker">Detail<input type="checkbox" id="admCustRptDtl" name="admCustRptDtl" class="admChkbx"></td>
</tr>
```
---
```
$(function() { $('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admCustBtn").click(function()
{ // validate and process form
// first hide any error messages
$('.error').hide();
var admCustRPSecPhone =
$("input#admCustRPSecPhone").val();
var admCustRptDly =
$("checkbox#admCustRptDly").val();
var admCustRptSumm =
$("checkbox#admCustRptSumm").val();
var admCustRptDtl =
$("checkbox#admCustRptDtl").val();
var dataString =
'admCustID='+ admCustID +
'&admCustRptDly='+ admCustRptDly +
'&admCustRptSumm='+ admCustRptSumm +
'&admCustRptDtl='+ admCustRptDtl;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
alert( "Success! Data Saved");
}
});
return false; }); });
``` | Your selectors for the checkboxes are not correct.
```
var admCustRPSecPhone = $("input#admCustRPSecPhone:checked").val() == 'on';
var admCustRptDly = $("input#admCustRptDly:checked").val() == 'on';
var admCustRptSumm = $("input#admCustRptSumm:checked").val() == 'on';
var admCustRptDtl = $("input#admCustRptDtl:checked").val() == 'on';
```
You could also use something like:
```
var admCustRptDly = $("#admCustRptDly:checkbox:checked").val() == 'on';
```
This will set the values to true/false depending on whether the checkbox is checked or not. | Actually both..
the checkboxes don't have value, so if you try to alert() their values it will lead to "undefined", but if you are facing this on alerting the checkbox itself you are probably doing something wrong.
Setting their values to true, won't lead to anything, as @Soviut said, most properties repeat their names on setting. So your input will get like:
```
<input type="checkbox" checked="checked" value="1" name="myCheck" />
```
So, try the above and give us some feedback =´p | JQuery submitted values for checkboxes are undefined | [
"",
"javascript",
"jquery",
""
] |
I have 2 **static** objects in 2 **different dlls**:
An object *Resources* (which is a singleton), and an object *User*. Object User in its destructor has to access object Resources.
How can I force object Resources not to be destructed before object User? | Global objects are destroyed when their corresponding DLL is unloaded. So as your 'User' dll is probably dependent of your 'Resource' dll, you are in trouble: 'resource' will always be destroyed before 'user'.
I'm also interested by a good answer to this question, if one exist. Until now, I'm using a cleanup function that must be called by application before it quits, and I only keep harmless code in destructors. | If you are able to put that 2 global variables in the same DLL it's not the same story. As told by Jem in its own reply, DLL detachement order is not guaranteed by the system. Therefore you may have a big problem when having 2 separated Dlls. I am not a Windows system guru, but having a look with google, I found msdn bloggers who tells they had the same issue with no good solution to address it.
I you are able to put them in one same DLL, according to me the solution is easier, in that case you don't need to address the "not garanteed DLL detachement order" issue (unsolvable as far as I understand).
But then you still need to address a new issue: global variable destruction order is not garanteed by the c++ language. But this one can be addressed:
you need to use some kind of reference couting. a boost::shared\_ptr may do the trick.
Declare it global and define it that way:
```
boost::shared_ptr my_resource_ptr ( new Resource() ); // new operator is important here!
```
Then you need to modify your User implementation to **store** its own shared\_ptr:
```
class User
{
...
boost::share_ptr a_resource_ptr;
...
};
```
As long as all one of your User instance is not destroyed, those will 'retain' the Resource instance, and so prevent it from being prematuraly deleted, even though the global shared\_ptr could have been destroyed.
The last User instance being destroyed will (undirectly) delete the Resource instance.
Whatever the reference counting you use, ComPtr, your own, it should do the trick. | How to force destruction order of static objects in different dlls? | [
"",
"c++",
"dll",
"static",
"destructor",
""
] |
I'm looking for a profiler for my C# application being developed in Visual Studio 2008. I am looking for something that is inexpensive (open sourced is preferred) and that it can integrate into VS2008. I found the [Visual Studio Profiler](http://blogs.msdn.com/ianhu/archive/2005/02/07/368779.aspx) but I do not know how to use it. I installed the Stand Alone version which depends on Visual Studio (not to stand alone I guess?) but nothing ever shows up in the Tools menu like their walk through says it will. | Here's a list of open source .Net [profilers](http://csharp-source.net/open-source/profilers).
I have used and like the [Ants-Profiler](http://www.red-gate.com/products/ants_performance_profiler/index.htm) from Red Gate, but it does cost money (highly worth it, IMHO). | The Visual Studio Profiler is part of Team System only. It is not included in Visual Studio Professional.
There is a free .NET profiler called [nprof](http://code.google.com/p/nprof/), but it's not released yet and it can be rather volatile. Also, there are some excellent commercial profiler's such as [ANTS Profiler from Red Gate](http://www.red-gate.com/products/ants_performance_profiler/index.htm); however, these are not low cost. | Where can I find a profiler for C# applications to be used in Visual Studio 2008? | [
"",
"c#",
"visual-studio-2008",
"profiling",
""
] |
I have a function, say:
```
setValue: function(myValue) {
...
}
```
The caller might pass a string, number, boolean, or object. I need to ensure that the value passed further down the line is a string. What is the safest way of doing this? I realize there are many ways some types (e.g. Date) could be converted to strings, but I am just looking for something reasonable out of the box.
I could write a series of typeof statements:
```
if (typeof myValue == "boolean") {}
else if () {}
...
```
But that can be error-prone as types can be missed.
Firefox seems to support writing things like:
```
var foo = 10; foo.toString()
```
But is this going to work with all web browsers? I need to support IE 6 and up.
In short, what is the shortest way of doing the conversion while covering every single type?
-Erik | ```
var stringValue = String(foo);
```
or even shorter
```
var stringValue = "" + foo;
``` | ```
value += '';
``` | What is the shortest way of converting any JavaScript value to a string? | [
"",
"javascript",
""
] |
I understand that Outlook has set items, i.e. Mail, Task, Calendar, Notes, etcetera. How can you create a custom Item that Outlook will recognize as the others? I know that when you add the Business Contact Manager it creates Items like "Opportunities"
Can you override an Item, or inherit an Item and alter/add properties and methods?
examples:
```
olAppointmentItem 1 Represents an AppointmentItem
olContactItem 2 Represents a ContactItem
olDistributionListItem 7 Represents an DistListItem
olJournalItem 4 Represents a JournalItem
olMailItem 0 Represents a MailItem
olNoteItem 5 Represents a NoteItem
olPostItem 6 Represents a PostItem
olTaskItem 3 Represents a TaskItem
``` | > You cannot create new "types"; but you
> can certainly re-use the existing
> types by adding your own properties.
That comment is not correct. you can certainly use custom forms, you just need to publish them first to a forms library, and make them accesible to users. generally they are based on the design of one of the default item types, and can also be associated with a folder as the default item type.
Edit: (updating post as per comment request)
A.Create and publish a custom form - <http://office.microsoft.com/en-au/outlook/HA012106101033.aspx>
B. programmatically create an instance of the custom form.
```
Outlook.Application olApp = new Outlook.Application();
//mapifolder for earlier versions (such as ol 2003)
Outlook.Folder contacts = olApp.Session.GetDefaultFolder(Outlook.olDefaultFolders.olFolderContacts);
//must start with IPM. & must be derived from a base item type, in this case contactItem.
Outlook.ContactItem itm = (Outlook.ContactItem)contacts.Items.Add(@"IPM.Contact.CustomMessageClass");
itm.Display(false);
``` | Outlook has the ability to create custom forms. You use the forms designer bultin to outlook, there is one built all versions of Outlook. You can launch a design session with the Tools | Forms | Design a Form command. Alternatively, open any Outlook item in Outlook 2003 or earlier and choose Tools | Forms | Design This Form.
When you design a form you start based on on of the exiting form such a appointment, task etc.. The closest thing to a blank form is the post form.
Forms can have VBScript code behind them to react to user actions -- validating data, synchronizing it with databases, creating new Outlook items, etc. To add code, once you're in form design mode, click the View Code command on the toolbar or ribbon.
You can then publish you form into the Organization Forms library, so that everyone has access to them. They can also be published directly to a folder. Personal forms are published either to a folder or to your Personal Forms library.
There is quite a lot of help documentation for this kind of thing in Outlook Help, also google will return loads of sites that show you how. | How do I create a custom Outlook Item? | [
"",
"c#",
"outlook",
"vsto",
"outlook-addin",
""
] |
I'll explain what I'm trying to achieve:
I want to have a situation where I can create as many controls as I want by creating them in a loop in the code behind. I can do this while using PHP, by mixing the PHP code and the HTML code. This allows me to generate actual HTML tags dynamically.
In ASP.NET, I haven't found a way to replicate this functionality.
I've thought about using a loop in the code behind on something like the Init() function to create an array of new() objects, setting their attributes and hoping it is passed into the aspx file, but it didn't work.
How do I do this? | If you want to creat Dynamically ASP.Net Hyperlink control
You can simply do this:
```
HyperLink hyp = new HyperLink();
hyp.ID = "hypABD";
hyp.NavigateUrl = "";
Page.Controls.Add(hyp);
``` | Well, keep in mind there's a difference between Hyperlinks and LinkButtons in ASP.Net
If you just want Hyperlinks, you can create as many as you want by creating a HyperLink object, creating new objects and then adding them to some control's Controls collection like panel or span or something.
LinkButtons are a little different. You have to use a Repeater control if you want to create a link that posts back to the server. (Well, you don't have to but the alternative is a hack job.)
Hyperlinks can be created by using a Repeater control as well and, if possible is the method I would recommend. | How do I dynamically create new Hyperlinks in ASP.NET? | [
"",
"c#",
".net",
"asp.net",
"visual-studio",
"hyperlink",
""
] |
I have implemented a csv file builder that takes in an xml document applies a xsl transform to it and appends it to a file.
```
public class CsvBatchPrinter : BaseBatchPrinter
{
public CsvBatchPrinter() : base(".csv")
{
RemoveDiatrics = false;
}
protected override void PrintDocuments(System.Collections.Generic.List<XmlDocument> documents, string xsltFileName, string directory, string tempImageDirectory)
{
base.PrintDocuments(documents, xsltFileName, directory, tempImageDirectory);
foreach (var file in new DirectoryInfo(tempImageDirectory).GetFiles())
{
var destination = directory + file.Name;
if (!File.Exists(destination))
file.CopyTo(destination);
}
}
protected override void PrintDocument(XmlDocument document, string xsltFileName, string directory, string tempImageDirectory)
{
StringUtils.EscapeQuotesInXmlNode(document);
if (RemoveDiatrics)
{
var docXml = StringUtils.RemoveDiatrics(document.OuterXml);
document = new XmlDocument();
document.LoadXml(docXml);
}
using (var writer = new StreamWriter(string.Format("{0}{1}{2}", directory, "batch", FileExtension), true, Encoding.ASCII))
{
Transform(document, xsltFileName, writer);
}
}
public bool RemoveDiatrics { get; set; }
}
```
I have a large number of xml documents to add to this csv file and after multiple calls to it, it occasionally throws an IOException `The process cannot access the file 'batch.csv' because it is being used by another process.`
Would this be be some sort of locking issue?
Could it be solved by:
```
lock(this)
{
using (var writer = new StreamWriter(string.Format("{0}{1}{2}", directory, "batch", FileExtension), true, Encoding.ASCII))
{
Transform(document, xsltFileName, writer);
}
}
```
**EDIT:**
Here is my stack trace:
```
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
at Receipts.Facade.Utilities.BatchPrinters.CsvBatchPrinter.PrintDocument(XmlDocument document, String xsltFileName, String directory, String tempImageDirectory) in CsvBatchPrinter.cs:line 37
at Receipts.Facade.Utilities.BatchPrinters.BaseBatchPrinter.PrintDocuments(List`1 documents, String xsltFileName, String directory, String tempImageDirectory) in BaseBatchPrinter.cs:line 30
at Receipts.Facade.Utilities.BatchPrinters.CsvBatchPrinter.PrintDocuments(List`1 documents, String xsltFileName, String directory, String tempImageDirectory) in CsvBatchPrinter.cs:line 17
at Receipts.Facade.Utilities.BatchPrinters.BaseBatchPrinter.Print(List`1 documents, String xsltFileName, String destinationDirectory, String tempImageDirectory) in BaseBatchPrinter.cs:line 23
at Receipts.Facade.Modules.FinanceDocuments.FinanceDocumentActuator`2.printXmlFiles(List`1 xmlDocuments, String tempImagesDirectory) in FinanceDocumentActuator.cs:line 137
```
and my base class:
```
public abstract class BaseBatchPrinter : IBatchPrinter
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected readonly string FileExtension;
protected BaseBatchPrinter(string fileExtension)
{
FileExtension = fileExtension;
}
public void Print(List<XmlDocument> documents, string xsltFileName, string destinationDirectory, string tempImageDirectory)
{
Log.InfoFormat("Printing to directory: {0}", destinationDirectory);
PrintDocuments(documents, xsltFileName, destinationDirectory, tempImageDirectory);
}
protected virtual void PrintDocuments(List<XmlDocument> documents, string xsltFileName, string directory, string tempImageDirectory)
{
foreach (var document in documents)
{
PrintDocument(document, xsltFileName, directory, tempImageDirectory);
}
}
/// <summary>
/// Needs to Call Transform(XmlDocument document, string xsltFileName, string directory)
/// </summary>
protected abstract void PrintDocument(XmlDocument document, string xsltFileName, string directory, string tempImageDirectory);
protected void Transform(XmlDocument document, string xsltFileName, StreamWriter writer)
{
//TODO: look into XslCompiledTransform to replace the XslTransform
var xslTransform = new XslTransform();
xslTransform.Load(xsltFileName);
xslTransform.Transform(createNavigator(document), null, writer);
}
protected string CreateFileName(string directory, XmlDocument doc)
{
var conId = createNavigator(doc).SelectSingleNode(Config.SELECT_CONSTITUENT_ID_XPATH).Value;
return string.Format(@"{0}{1}{2}", directory, conId, FileExtension.IndexOf('.') > -1 ? FileExtension : "." + FileExtension);
}
protected XPathNavigator createNavigator(XmlDocument document)
{
return document.DocumentElement == null ? document.CreateNavigator() : document.DocumentElement.CreateNavigator();
}
}
```
Cheers. | Hey all thanks for your responses.
I have come up with a solution that works for me. A little bit hacky but it does the job.
```
protected override void PrintDocument(XmlDocument document, string xsltFileName, string directory, string tempImageDirectory)
{
StringUtils.EscapeQuotesInXmlNode(document);
if (RemoveDiatrics)
{
var docXml = StringUtils.RemoveDiatrics(document.OuterXml);
document = new XmlDocument();
document.LoadXml(docXml);
}
IOException ex = null;
for (var attempts = 0; attempts < 10; attempts++)
{
ex = tryWriteToFile(document, directory, xsltFileName);
if (ex == null)
break;
}
if (ex != null)
throw new ApplicationException("Cannot write to file", ex);
}
private IOException tryWriteToFile(XmlDocument document, string directory, string xsltFileName)
{
try
{
using (var writer = new StreamWriter(new FileStream(string.Format("{0}{1}{2}", directory, "batch", FileExtension), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.ASCII))
{
Transform(document, xsltFileName, writer);
writer.Close();
}
return null;
}
catch (IOException e)
{
return e;
}
}
```
Basically the idea behind it is to attempt to run it a couple of times and if the problem persists throw the error.
Gets me through the issue | Only one thing can cause this. Another process is writing to the file. The other process could even be your own.
I suggest you add try/catch blocks around the areas that can write that file. In the catch block, throw a new exception, adding the full file path:
```
var filePath = string.Format("{0}{1}{2}", directory, "batch", FileExtension);
try {
using (var writer = new StreamWriter(filepath, true, Encoding.ASCII)) {
Transform(...);
}
}
catch (IOException ex) {
throw new Exception(
String.Format("Exception while transforming file {0}", filePath),
ex);
}
```
Post the complete exception you receive, including any InnerException and stack trace.
You also want to make sure of whether your file copy could even be writing to batch.csv. | Getting an IOException on multiple writes to a file | [
"",
"c#",
"csv",
"ioexception",
""
] |
i found the following solution to add sorting capabilities to jQuery (ref: [jQuery sort()](http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/ "jQuery sort()")). I've altered the solution to sort strings of unknown length. It works nicely, however as you might notice from the function name: it sorts acscending :-).
```
jQuery.fn.sort = function() {
return this.pushStack( [].sort.apply( this, arguments ), []);
};
function sortStringAscending(a,b){
var h1 = a.innerHTML;
var h2 = b.innerHTML;
var c = 0;
var str1 = null,
var str2 = null;
while(str1 == str2 && (c < h1.length && c < h2.length)) {
str1 = h1.substring(c,c+1).toLowerCase().charCodeAt(0);
str2 = h2.substring(c,c+1).toLowerCase().charCodeAt(0);
if(str1 > str2) {
r = 1;
} else if(str2 > str1) {
r = -1;
}
c += 1;
}
return r;
};
```
The function is used like this:
```
$('ol li').sort(sortStringAscending).appendTo('ol');
```
**Is it possible to alter this code in such a way that the following will become possible?**
```
$('ol li').sort(sortString, 0).appendTo('ol'); //0 for descending
$('ol li').sort(sortString, 1).appendTo('ol'); //1 for ascending
``` | You are not going to be able to easily get an additional argument into the array sort function that the jQuery.fn.sort uses.
It will be easier to use two separate functions, one for ascending, and one for descending, but keep the actual comparision in a third function.
```
function sortStringAscending(a,b) {
return sortString(a,b,1);
};
function sortStringDescending(a,b) {
return sortString(a,b,-1);
};
function sortString(a,b,direction) {
var h1 = a.innerHTML.toLowerCase();
var h2 = b.innerHTML.toLowerCase();
if(h1 > h2) {
r = 1*direction;
} else if(h2 > h1) {
r = -1*direction;
}
return r;
};
```
Also note that you can simply compare two strings, there is no need to compare them character by character, unless you want to have unpredictable sort order for items like "abc" and "abcd".
Then you should be able to do
```
$('ol li').sort(sortStringAscending).appendTo('ol');
$('ol li').sort(sortStringDescending).appendTo('ol');
``` | Changing this:
```
if(str1 > str2) {
r = 1;
} else if(str2 > str1) {
r = -1;
}
```
to this:
```
if(str1 > str2) {
r = -1;
} else if(str2 > str1) {
r = 1;
}
```
will swap the sort order.
---
EDIT:
Because of the way Javascript's array.sort(callback) function work it is not easy to just add a third parameter for the callback to accept, I will suggest using 2 separate functions mySortAsc and mySortDesc which in turn could be calling a third function and passing whatever parameters are needed. | How to customize this already custom jQuery sort solution? | [
"",
"javascript",
"jquery",
"arrays",
"sorting",
""
] |
Can any one give a simple method using JavaScript to display a status message while file is uploading and fade away when file is uploaded? | ```
<style type="text/css">
#loadingMessage {
position: absolute;
top: WHEREVER;
left: WHEREEVER;
z-Index: 100;
}
</style>
<div id="loadingMessage" style="visibility:hidden;">This page be uploading!</div>
<form id="yourForm"> ... </form>
<script>
document.getElementById("yourform").onsubmit = function() {
document.getElementById("loadingMessage").visibilty = "visible";
return true;
};
</script>
``` | > Using Jquery plugins you can apply many
> effects while uploading and after
> uploaded.
Check out this demo links :
<http://valums.com/wp-content/uploads/ajax-upload/demo-prototype.htm>
<http://www.uploadify.com/demo/>
Jquery Example :
<http://valums.com/ajax-upload/> | How can I display a status message while a file is uploading? | [
"",
"javascript",
"jsp",
""
] |
Problem:
You are given dates in a format of YYYYddd, which is the year, followed by the day of the year, 1 through 365(366). For example today would be 2009135 (5/15/2009).
What is the best way to create a new datetime from this? In Ruby I know there is a constructor that takes two numbers like so
```
Date.ordinal(2009, 135)
```
Is there a similar Constructor for C#? | Hmm, I am not sure if there is a more direct way, but this should work
```
new DateTime(year, 1, 1).AddDays(day - 1);
``` | How about:
```
new DateTime(ordinal / 1000, 1, 1).AddDays((ordinal % 1000) - 1);
```
This relies on day 1 of 2009 being represented as 2009001 rather 20091 though. If it's the latter, it's slightly trickier (although still not exactly hard, of course).
I would try to move away from such a format fairly quickly though - it's not exactly a common one, and it's completely unreadable. Assuming the "2009001" format it at least sorts reasonably, but I can't think of much else in its favour. | Ordinal Date Format C# | [
"",
"c#",
"datetime",
"ordinal",
""
] |
After using the Django template language, I really miss being able to do things like this:
```
{% if condition %}
<!-- snip -->
{% else %}
<!-- snip -->
{% endif %}
```
When I am using JSP, I am stuck doing something like this:
```
<logic:equal name="something" value="example">
<!-- snip -->
</logic:equal>
<logic:notEqual name="something" value="example">
<!-- snip -->
</logic:notEqual>
```
or:
```
<% if (condition) { %>
<!-- snip -->
<% } else { %>
<!-- snip -->
<% } %>
```
Is it possible to write a custom tag that supports `else` and `else if`, rather than simply having a pair of tags for each check?
If it's not possible, which is the "preferred" style? Scriptlets or multiple tag pairs? At my organization, most people seem to frown upon scriptlets, but I haven't really heard a good reason why simple conditional statements like the ones I've listed are so bad. | The tags in XML come in pairs, one to open one to close. The three elements of the if then else end do not lend to a nice open and close format. The only other way is to use the choose tag as follows:
```
<c:choose>
<c:when test="${bean.value == 2}">
<p>True</p>
</c:when>
<c:otherwise>
<p>False</p>
</c:otherwise>
</c:choose>
```
This is the usual way in which to code the if then else structures in jstl. | The JSTL tags come with a choose tag that works like a multi select.
```
<c:choose>
<c:when test="${first condition}">
whatever
</c:when>
<c:when test="${second condition}">
whatever
</c:when>
<c:when test="${third condition}">
whatever
</c:when>
<c:otherwise>
whatever else
</c:otherwise>
</c:choose>
``` | JSP Custom Tags: Is it possible to have a more than start / close tags? | [
"",
"java",
"jsp",
"coding-style",
"django-templates",
"custom-tag",
""
] |
As far as I can tell, there's no reason I shouldn't be allowed to pass a reference to a pointer in C++. However, my attempts to do so are failing, and I have no idea why.
This is what I'm doing:
```
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfunc(&s);
// ...
}
```
And I'm getting this error:
> cannot convert parameter 1 from 'std::string \*' to 'std::string \*&' | Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:
```
string s;
string* _s = &s;
myfunc(_s);
```
should compile just fine.
However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object. | The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is `const`.
So you can do one of either the following:
```
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
void myfunc2(string* const& val)
{
// Do stuff to the string pointer
}
int main()
// sometime later
{
// ...
string s;
string* ps = &s;
myfunc( ps); // OK because ps is not a temporary
myfunc2( &s); // OK because the parameter is a const&
// ...
return 0;
}
``` | Passing references to pointers in C++ | [
"",
"c++",
"pointers",
"reference",
""
] |
I'm new at WPF and C# and I'd like to know the best way of accessing MySQL.
Googling a little bit I've seen there's a Linq provider for MySQL. Is that the best way?
<http://code2code.net/DB_Linq/>
I've never used Linq before so I'll start today unless somebody knows a better way of doing that.
Thanks in advance | You should use the official [MySQL ADO.NET provider](http://dev.mysql.com/downloads/connector/net/6.0.html). Version 6.0 introduces basic support for Entity Framework | It depends! If I were coaching someone who was just starting out, I wouldn't start them out on LINQ. You said you were just starting with C#, but maybe you have some depth in other environments, particularly with databases and maybe you are familiar with ORM. IF that is true, then by all means dive head first into LINQ. If not, then I'd suggest using ADO.NET for your database access in your first projects - it is simpler to start with and is somewhat foundational for other alternatives. | Ways of accessing MySQL from C#/WPF | [
"",
"c#",
"mysql",
"wpf",
"linq",
""
] |
anyone know of a free open-source jpeg encoding library for C/C++? Currently I'm using ImageMagick, which is easy to use, but it's pretty slow. I compared it to an evaluation of Intel Performance Primitives and the speed of IPP is insane. Unfortunately it also costs 200$, and I don't need 99% of the IPP). Also it will only work fast on Intel.
Anyone do any tests? Any other good libraries out there faster than ImageMagick?
Edit: I was using 8 bit version of ImageMagick which is supposed to be faster. | ImageMagick uses libjpeg (a.k.a Independent JPEG Group library). If you improve the speed of libjpeg, ImageMagick JPEG speed will increase.
There are a few options:
1. Compile an optimized libjpeg. If you have a modern gcc and at least a Pentium 4, you can try `-O3 -msse2` and see if it can boost your speed. Then you can use `LD_LIBRARY_PATH` or some other way to load your libjpeg instead of the system one.
2. Try out libjpeg-mmx. It is unmaintained, and supposedly buggy and with security flaws, but it may give a speed boost in your case. | Check out libjpeg/SIMD, in the trunk of TigerVNC (<http://www.tigervnc.com>). We have optimized 64-bit and 32-bit versions which are almost as fast as IPP at compressing/decompressing baseline JPEG:
<http://www.mail-archive.com/tigervnc-devel@lists.sourceforge.net/msg00403.html> | Fast JPEG encoding library | [
"",
"c++",
"c",
"encoding",
"jpeg",
""
] |
What is the best way to create the matrix `C`?
```
string A;
char[] B = A.ToCharArray();
string[] C = new string[B.Length];
for (int i = 0; i < B.Length ; i++)
{
C[i] = B[i].ToString();
}
``` | You just want a nicer way to do what you're doing? I suppose you could do it like this:
```
string A = "ABCDEFG";
string[] C = A.Select(c => c.ToString()).ToArray();
``` | Another option as well as mquander's is to use [`Array.ConvertAll()`](http://msdn.microsoft.com/en-us/library/exc45z53.aspx):
```
string[] C = Array.ConvertAll(A.ToCharArray(), c => c.ToString());
```
I generally prefer the LINQ approach, but `ConvertAll` is worth knowing about (for both arrays and lists) as it's able to use the fact that it knows the size to start with. | How can I create a string array of each character in a string in C#? | [
"",
"c#",
""
] |
I made a program in which I wanted to manually update the Data Grid View.
-I have a Method to Refresh the DGV by clearing it and then reinserting the data.
-Using the designer, I made an event handler for the DGV's CellEndEdit. Inside the Event Handler, the data gets updated & the DGV's custom refreshing method is called.
While running the program, whenever I start editing a cell & end it by selecting another one, an exception is thrown:
InvalidOperationException
Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.
Visual C#'s debugger marks the line that clears the data : datagridview1.Rows.Clear();
If you'd like to reproduce the problem, Make a new windows form project with visual c#, put a DataGridView object on the form, and paste the following code for the Form1.cs:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Error___DataGridView_Updating___Cell_endedit
{
public partial class Form1 : Form
{
// Objects
DataTable dt;
DataColumn colID;
DataColumn colName;
DataColumn colInfo;
// Constructor
public Form1()
{
InitializeComponent();
Initialize_dt();
InsertSampleData_dt();
Initialize_dataGridView1();
}
// Methods
private void Initialize_dt()
{
dt = new DataTable();
// Building Columns
// ID
colID = new DataColumn();
colID.ColumnName = "ID";
colID.DataType = typeof(int);
dt.Columns.Add(colID);
// Name
colName = new DataColumn();
colName.ColumnName = "Name";
colName.DataType = typeof(string);
dt.Columns.Add(colName);
//Info
colInfo = new DataColumn();
colInfo.ColumnName = "Info";
colInfo.DataType = typeof(string);
dt.Columns.Add(colInfo);
}
private void InsertSampleData_dt()
{
DataRow row;
// 0
row = dt.NewRow();
row["ID"] = 100;
row["Name"] = "AAAA";
row["Info"] = "First Record";
dt.Rows.Add(row);
//1
row = dt.NewRow();
row["ID"] = 101;
row["Name"] = "BBBB";
row["Info"] = "Second Record";
dt.Rows.Add(row);
//2
row = dt.NewRow();
row["ID"] = 102;
row["Name"] = "CCCC";
row["Info"] = "Third Record";
dt.Rows.Add(row);
}
private void Initialize_dataGridView1()
{
dataGridView1.AllowUserToAddRows = false;
// Data Grid Definitions
// Row Header
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
// ColumnHeaders
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// Building Columns
#region ID
{
DataGridViewColumn colSGID = new DataGridViewTextBoxColumn();
colSGID.Name = "ID";
colSGID.HeaderText = "#";
colSGID.ReadOnly = true;
colSGID.Visible = false;
colSGID.Resizable = DataGridViewTriState.False;
dataGridView1.Columns.Add(colSGID);
}
#endregion
#region Name
{
DataGridViewColumn colSGName = new DataGridViewTextBoxColumn();
colSGName.Name = "Name";
colSGName.HeaderText = "Name";
dataGridView1.Columns.Add(colSGName);
}
#endregion
#region Info
{
DataGridViewColumn colSGSubject = new DataGridViewTextBoxColumn();
colSGSubject.Name = "Info";
colSGSubject.HeaderText = "Description";
dataGridView1.Columns.Add(colSGSubject);
}
#endregion
Refresh_dataGridView1();
}
private void Refresh_dataGridView1()
{
int index;
dataGridView1.SuspendLayout();
dataGridView1.Rows.Clear();
//MessageBox.Show("Cleared Data. Rebuilding...");
foreach (DataRow row in dt.Rows)
{
index = dataGridView1.Rows.Add(new DataGridViewRow());
dataGridView1.Rows[index].Cells["ID"].Value = row["ID"];
dataGridView1.Rows[index].Cells["Name"].Value = row["Name"];
dataGridView1.Rows[index].Cells["Info"].Value = row["Info"];
//MessageBox.Show("row #" + index);
}
dataGridView1.ResumeLayout();
}
//Event Handlers
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
bool toUpdate = false;
int id = (int)dataGridView1.Rows[e.RowIndex].Cells["ID"].Value;
string columnName = dataGridView1.Columns[e.ColumnIndex].Name;
string value = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (value == null)
{
value = string.Empty;
}
switch (columnName)
{
case "Name":
if (value == string.Empty)
{
MessageBox.Show("Name Can't Be Empty!");
}
else
{
toUpdate = true;
}
break;
case "Info":
toUpdate = true;
break;
}
if (toUpdate)
{
foreach(DataRow row in dt.Rows)
{
if ( (int)row["ID"] == id)
{
row[columnName] = value;
}
}
Refresh_dataGridView1();
}
}
}
}
``` | There's an answer by Bruce.Zhou at MSDN forums. I posted here a snippet from it. [Here](http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/7970b78b-4fb6-4138-b49e-fc3e665f866c) also is the link to the original post.
```
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
...................................................;
if (toUpdate)
{
foreach(DataRow row in dt.Rows)
{
if ( (int)row["ID"] == id)
{
row[columnName] = value;
}
}
this.BeginInvoke(new MethodInvoker(Refresh_dataGridView1));
}
}
```
> ...
When using this fix, whenever the new cell is selected, all the cells between it and the first cell (including) are selected. I am looking for a way to select only the new cell. | i knocked my head against the keyboard for the last hour to solve this issue.
here is my workaround:
looking at the problem: when selecting another cell (or any control within the gridview) EndEdit is triggered.
apply the following check before applying your edit:
```
public void myGrid_EndEdit(object sender, DataGridViewCellEventArgs e)
{
if (!myGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
return;
//...rest of your code to apply edit below...
}
```
This should apply to any cell being edited.(thus edit is not applied when losing focus; Typing Enter would suffice to apply the edit) | InvalidOperationException - When ending editing a cell & moving to another cell | [
"",
"c#",
"datagridview",
"invalidoperationexception",
""
] |
Greetings!
Working on a web based project were business rules and logic need to be customized by client. I want to do this without having to recompile the application every time we sign up a new client on the system. The architectures I have outlined so far are:
1. Windows Workflow: Creating dynamic workflows and saving them to the database.
2. Reflection: Creating a business rules interface and use reflection to load the custom client assembly.
3. A true business rules engine
4. Implementing an IOC Container like structure map. [zaff: added 6/4]
Have you ever implemented anything similar to this? If so, what is your experience? And finally is there another solution that I should be exploring?
Thanks for your help!! | I have implemented most of the approaches you mention. The answer may depend on a variety of factors.
What client role(s) will be making the changes to the business rules (e.g. business analyst, developer, power user, etc.)? Meaningful support for business analysts may require a rules engine with externalized rules in a db and a useable UI. Meaningful support for developers might be as simple as leveraging something like MEF (<http://www.codeplex.com/MEF>).
You might also factor in how often will the business rules need to be changed and what sorts of associated operational requirements may apply (e.g. host process must remain running, app domain unloading ok, etc.). A good selection may require some careful thought about likely vs. unlikely future needs. | You can do data driven business rules, like [this](http://www.tdan.com/view-articles/5227/). Decision trees can be a good way to go as well.
You might also think about aspect-oriented programming as a way to implement business rules.
My only caution with a Rete induction rules engine is that the rule sets should be kept small and close to the objects that use them. If you can encapsulate the behavior of an object in a rules engine that's part of its state, all the better. I don't care for the "enterprise" solution that dumps thousands of rules into a singleton rules engine that becomes a dependency for every part of the enterprise. | Dynamic Business Rules in a web application | [
"",
"c#",
"asp.net",
"inversion-of-control",
"workflow-foundation",
"business-logic",
""
] |
Soon I will have to start a web project for a company, and I now need to choose a technology to build the app.
I'm thinking about using Java, hence I'd like to find a framework that will help me building the app (I'm used to PHP framework such as CakePHP & CodeIgniter).
What I don't understand is that it seems to exist a lot of framework and technologies that don't have the same goal. Action framework, Component framework ... what can I do with one I can't do with another ?
It seems a java web app should be developped by mixing a lots of different technologies, hence I'm a bit lost ...
I've had a look at differents java frameworks, such as JSF, Stripes, Struts2, Tapestry, Wicket and Spring.
About the later, I don't quiet see what are the different parts of this framework, what can it do for me and what it can't. What can I take from Spring and what I don't need...
Hence : what do I need to build a java web application ?
I've already used JSF for a basic CRUD app, but I'm trying to find something that may better suits my need.
The app we'll have to build will be both a community platform as well as a merchant site, with sensible datas to protect :)
About the ORM, I guess I'll just go with Hibernate ...
Also I've heard about Maven or Ant, in what way can they help me ?
Any advice/guideline would be much appreciated :-)
Thanks in advance.
Edit : what my needs are : a java framework that is :
* well documented / easy to get help / as easy as possible ...
* the more java, the better
* Ajax friendly / Facility to build nice UI ...
* Internationalization
* Still being a student, Marketability of Skills might matters ...
The app to be build is both a
* Community site : web 2.0, CRUD
* E-commerce site
full specs aren't finished yet. | This is a very tough question to answer, having been in your situation recently I will try to give some insight. Basically, with Java there is a ton of choice for frameworks and no one can really tell you which one is best-fit for you, what we can do is give you a breakdown of some of the technologies.
The following is what I have come across in search of the same answers you want.
Java has a bunch of technologies that try to provide a full-stack solution. These technologies can be broken up into other technologies but work well when you use them together.
Basically, there are 3 tiers to web applications, the presentation, business and data tier. The presentation tier is the front end, what the user sees. You can generally mix and match technologies for these three layers. You could for example use a stripes front-end with the Spring framework for IOC and Hibernate as your ORM.
There are many great technologies that you can use for the presentation layer, including Spring-MVC, STRUTS, Stripes, Wicket, JSF/SEAM and Tapestry among a few. Most of these use a JSP for the view using JSTL, with the exception of wicket which actually full separates the html from the logic by using Java "components" (POJOS). There are benefits and drawbacks to both approaches. The benefit of the wicket approach is that you have static typechecking and a complete separation of the html so you can hand it off to your designer.
For the business layer generally people use some sort of Inversion of Control framework (IOC) for Dependency Injection (DI). The popular frameworks for IOC are Spring and Seam, these have associated technologies like Spring-security and generally are supported by the other technologies. Google Guice seems to be popular for a straight DI framework.
Finally, for the data layer most people tend to use Hibernate or JPA. There are others, but I have no experience with them and cannot offer any more information.
Tapestry is another framework that attempts to be a full stack from what I understand and takes a wicket like (or I guess Wicket takes a tapestry-like) approach. Grails is yet another full-stack framework using Groovy and built on top of Spring and Hibernate. If you like Rails, Grails is pretty good.
Most of these technologies have a lot of information available and very active mailing lists / IRC chatrooms. What you need to do is take a look at them and then decide which approach is the right one for you. No one here is able to tell you what you will like.
If you want a recommendation, I would like to one day use a Wicket/Guice/Hibernate stack. | My favourite is definitely Spring. The new Spring MVC 2.5 is easy and quick to set up, lots of annotations to help you wire your controllers declaratively which saves you a lot of typing. It also integrates with the Spring container which is definitely my favourite light-weight J2EE replacement container. I usually combine SpringMVC with simple JSP, but there are a lot of other view techs to choose from. For persistence I usually use Hibernate. Might be worthwhile to take a look at [Spring ROO](http://forum.springsource.org/showthread.php?t=71985) which is kind of like Grails without Groovy. Spring Security offers a nice and easy declarative way of doing security and integrates into a whole bunch of authentication technologies.
Maven and ant are both build tools while maven also handles dependencies for you. You "just" set up descriptors that describe the libraries you want and the version requirements, and maven will download all libraries and their dependencies for you. It forces you to follow a certain project layout, though. For ant there's ivy which does dependencies. | How to build a java web application | [
"",
"java",
"orm",
"user-interface",
"frameworks",
""
] |
Can people suggest the best tool to determine the cyclic complexity with in a C# winforms code base. | [NDepend](http://www.ndepend.com/) has a huge number of code analysis and query tools including [Cyclomatic Complexity](http://www.ndepend.com/docs/code-metrics#CC) per type and method estimation. | In Visual Studio I just go to Analyze/Calculate Code Metrics and I get cyclomatic complexity.
### 3rd party edit
* Visual Studio 2015 community edition has it as well | Best tool to determine code Cyclomatic complexity | [
"",
"c#",
"cyclomatic-complexity",
""
] |
One application causes a heavy load on our Sql Server 2005 database. **We don't control the application** that runs this query hundres of times a minute:
```
select id,col1,col2,col3 from table where id != id
```
Note the **id != id**, meaning a row is not equal to itself. Unsurprisingly, the result is always no rows found. However, Sql Server does a clustered index scan scan every time it runs this query!
The id column is defined as:
```
varchar(15) not null primary key
```
The query plan shows a huge number for "Estimated Number of Rows". Does anyone have an idea why Sql Server needs the table scan to figure out the obvious? | After reading the answers here and your edits, let me sum up your options:
1. Change MS SQL Server to handle this case (basically, talk to Microsoft support)
2. Change the application to avoid this case, or do it differently (basically, talk to support of the company that made the application)
3. Change to something other than SQL Server (if the application allows it), that handles this case
4. Change to another application
None of these are good solutions, but unfortunately, they're the only ones you have. You have to pick one, and go with it.
I would try solution 2 first, it is the one that would/should take the shortest time to execute.
If, on the other hand, that company is unwilling to change the application, then I would go with solution 4. This is a major performance bug, and if the company is unwilling or unable to fix that problem, you have to ask yourself, what else is lurking around the next corner? | I would fake this query out... abstract away with a view, and dupe the query.
Rename your existing table 'table' to 'table\_org' or something else, and create a view like this:
```
CREATE VIEW table
AS
SELECT * FROM table_org
WHERE id='BOGUSKEY'
```
Now, you should get your 1 scan through the table on the primary key, and it should (like the original query) find nothing. The application knows none the wiser... | Unexpected table scan for id != id | [
"",
"sql",
"sql-server",
"sql-server-2005",
"indexing",
""
] |
I have a hash table which can contain any number of objects. All of these objects implement some similar methods / properties and some of their own.
For example all objects in the hashtable may have a method called PrintText taking a single parameter of type string. All the objects are however instantiated from different classes.
Is it possible for me to pull out a particular object from the hashtable by its key without knowing its type before runtime, and access all its own methods and properties (not just the common ones)?
Normally I would do something like,
MyClass TheObject = MyHashTable[Key];
But the object being pulled out could be derived from any class so I cannot do that in this instance. | You could define an interface containing the common methods and properties, and implement this interface in all your classes. Then you can easily access these methods and properties.
But to access the specific methods of an object (not contained in the interface), you will need to know the type of the object.
Update:
It's not clear from your question, but when you write about a hashtable, I assume you mean the [Hashtable class](http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx). In that case, you should have a look at the [generic Dictionary class](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx) (available since .NET 2.0). This class will make your code typesafe and saves you from a lot of type-casting, e.g:
```
IMyInterface a = new MyObject();
// with Hashtable
Hashtable ht = new Hashtable();
ht.Add("key", a);
IMyInterface b = (IMyInterface)ht["key"];
// with Dictionary
var dic = new Dictionary<string, IMyInterface>();
dic.Add("key", a);
// no cast required, value objects are of type IMyInterface :
IMyInterface c = dic["key"];
``` | To solve problems with common methods and properties you can solve by making your classes to implement the same interface. However, I don't see how you can access non-common members. You can try to use Reflection. | Working with a hashtable of unknown but similar objects (C#) | [
"",
"c#",
".net",
"oop",
""
] |
Looking at the last JUnit test case I wrote, I called log4j's BasicConfigurator.configure() method inside the class constructor. That worked fine for running just that single class from Eclipse's "run as JUnit test case" command. But I realize it's incorrect: I'm pretty sure our main test suite runs all of these classes from one process, and therefore log4j configuration should be happening higher up somewhere.
But I still need to run a test case by itself some times, in which case I want log4j configured. Where should I put the configuration call so that it gets run when the test case runs standalone, but not when the test case is run as part of a larger suite? | The `LogManager` class determines which log4j config to use in a [static block](https://github.com/apache/log4j/blob/trunk/src/main/java/org/apache/log4j/LogManager.java#L81) which runs when the class is loaded. There are three options intended for end-users:
1. If you specify `log4j.defaultInitOverride` to false, it will not configure log4j at all.
2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to `java`:
`-Dlog4j.configuration=<path to properties file>`
in your test runner configuration.
3. Allow log4j to scan the classpath for a log4j config file during your test. (the default)
See also the [online documentation](http://logging.apache.org/log4j/1.2/manual.html#Default_Initialization_Procedure). | I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway) | Where do I configure log4j in a JUnit test class? | [
"",
"java",
"logging",
"junit",
"log4j",
""
] |
Using SQL Server 2005 Express.
```
(
CONVERT(VARCHAR(8), R.reviewStart, 108) between CONVERT(VARCHAR(8), M.meetingStart, 108) and CONVERT(VARCHAR(8), M.meetingEnd, 108) OR
CONVERT(VARCHAR(8), R.reviewEnd, 108) between CONVERT(VARCHAR(8), M.meetingStart, 108) and CONVERT(VARCHAR(8), M.meetingEnd, 108) OR
CONVERT(VARCHAR(8), M.meetingStart, 108) between CONVERT(VARCHAR(8), R.reviewStart, 108) and CONVERT(VARCHAR(8), R.reviewEnd, 108) OR
CONVERT(VARCHAR(8), M.meetingEnd, 108) between CONVERT(VARCHAR(8), R.reviewStart, 108) and CONVERT(VARCHAR(8), R.reviewEnd, 108)
)
```
Will the "between" still have the expected behavior after the datetimes have been converted to varchar?
Thanks | Yes, depending on what you mean by expected behavior. The BETWEEN operator will treat these operands as varchars, and apply its comparison rules accordingly:
> BETWEEN returns TRUE if the value
> of test\_expression is greater than or
> equal to the value of begin\_expression
> and less than or equal to the value of
> end\_expression.
Now, I can see a lot of potential problems, comparing strings and expecting date comparison behavior. I haven't seen any in my tests, but look carefully at your data. Is the CONVERT returning 24-hour time, with the appropriate leading zeroes?
[This question](https://stackoverflow.com/questions/807909/how-can-i-compare-time-in-sql-server) has some other approaches to comparing dateless-times, other than converting them to varchars.
Also, watch for null dates, which will cause the corresponding WHERE condition to return false (actually, unknown).
In your other question, you indicated that you were getting an error. If so, can you post that? | Your first condition is equivalent to this more index friendly one:
```
R.reviewStart >= DATEADD(day, DATEDIFF(day, '19010101', M.meetingStart), '19010101')
and R.reviewStart < DATEADD(day, 1+DATEDIFF(day, '19010101', M.meetingStart), '19010101')
```
(explained here:
[Reuse Your Code with Table-Valued UDFs](http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/05/23/reuse-your-code-with-cross-apply.aspx)
)
. | use 'between' with varchar (sql server) | [
"",
"sql",
"sql-server-2005",
"datetime",
"between",
""
] |
I have a table called `Transactions` with the following schema:
```
ColumnName DataType Constraints
---------- ---------- -----------
id int PK (Cluster-Index)
details varchar(50)
```
Later on, I add the following two columns to this table:
```
ColumnName DataType Constraints
---------- ---------- -----------
id int PK (Cluster-Index)
details varchar(50)
date datetime
comment varchar(255)
```
What will be the index performance on that table with the following query?
```
select * from transactions where id=somenumber
```
Will the performance change because I added the two columns? Will there be an effect on the clustered index? | Your performance will roughly be the same. Your clustered index defines the physical ordering of the rows. When you do a query on a clustered primary key, the database essentially does a binary search for your data. The result of adding columns means that not as many rows fit on the same data page. This means the database may have to do a bit more IO to get the same data. | > What will be the index performance on that table with the following query?
No discernible change (see below for why).
> Will the performance change because I added the two columns?
Yes, but minuscule. The actual search of the index will not be affected in any way because you're not changing the key at all.
The only impact is that you will be returning more data from your one record and that *may* result in a little more I/O but, since it's only for the one record, it's not relevant.
Even if there are not more I/O operations to retrieve the record itself, you will be transferring more data to the client. So technically, it's slower no matter what, but the difference between your previous schema and the changed one is not worth worrying about.
> Will there be an effect on the clustered index?
No, you have not changed any of the parameters in such a way to affect the primary key. | Index performance | [
"",
"sql",
"sql-server",
""
] |
I need to convert C# code to an equivalent XML representation.
I plan to convert the C# code (C# 2.0 code snippets, no generics or nullable types) to an AST and then convert the AST to XML.
Looking for a simple lexer/parser for C# which outputs an AST.
Any pointers on converting C# code to an XML representation (which can be converted back to C#) would also be very helpful.
Kind regards, | [MinosseCC: a lexer/parser generator for C#](http://www.codeproject.com/KB/recipes/minossecc.aspx)
Also SO questions:
[Parser-generator that outputs C# given a BNF grammar?](https://stackoverflow.com/questions/153572/parser-generator-that-outputs-c-given-a-bnf-grammar) which suggests using [ANTLR](http://www.antlr.org/)
[Translate C# code into AST?](https://stackoverflow.com/questions/213427/translate-c-code-into-ast)
[C# String to Expression Tree](https://stackoverflow.com/questions/821365/c-string-to-expression-tree)
[Developing a simple parser](https://stackoverflow.com/questions/391432/developing-a-simple-parser) | As Mitch says, Antlr can be your solution. You can transform Antlr's AST output depending on your needs and then serialize it with xstream. That's the approach I'm using in my bs project, If anyone knows a better way It'll be great for me aswell.
You can find csharp grammar samples like for example <http://www.antlr.org/grammar/1127720913326/tkCSharp.g> or <http://www.antlr.org/grammar/1151612545460/CSharpParser.g> but you might have to adapt it to ANTLRV3 or to your own needs. | Need to construct a XML representation for C# code | [
"",
"c#",
"parsing",
"tokenize",
""
] |
I thought this would be straightforward but apparently it isn't. I have a certificate installed that has a private key, exportable, and I want to programmatically export it with the public key ONLY. In other words, I want a result equivalent to selecting "Do not export the private key" when exporting through certmgr and exporting to .CER.
It seems that all of the X509Certificate2.Export methods will export the private key if it exists, as PKCS #12, which is the opposite of what I want.
Is there any way using C# to accomplish this, or do I need to start digging into CAPICOM? | For anyone else who might have stumbled on this, I figured it out. If you specify `X509ContentType.Cert` as the first (and only) parameter to `X509Certificate.Export`, it only exports the public key. On the other hand, specifying `X509ContentType.Pfx` includes the private key if one exists.
I could have sworn that I was seeing different behaviour last week, but I must have already had the private key installed when I was testing. When I deleted that certificate today and started again from scratch, I saw that there was no private key in the exported cert. | I found the following program helpful for reassuring myself that the `RawData` property of the certificate contains only the public key (MSDN is unclear on this), and that the answer above regarding `X509ContentType.Cert` vs. `X509ContentType.Pfx` works as expected:
```
using System;
using System.Linq;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
class Program
{
static void Main( string[] args )
{
var certPath = @"C:\blah\somecert.pfx";
var certPassword = "somepassword";
var orig = new X509Certificate2( certPath, certPassword, X509KeyStorageFlags.Exportable );
Console.WriteLine( "Orig : RawData.Length = {0}, HasPrivateKey = {1}", orig.RawData.Length, orig.HasPrivateKey );
var certBytes = orig.Export( X509ContentType.Cert );
var certA = new X509Certificate2( certBytes );
Console.WriteLine( "cert A : RawData.Length = {0}, HasPrivateKey = {1}, certBytes.Length = {2}", certA.RawData.Length, certA.HasPrivateKey, certBytes.Length );
// NOTE that this the only place the byte count differs from the others
certBytes = orig.Export( X509ContentType.Pfx );
var certB = new X509Certificate2( certBytes );
Console.WriteLine( "cert B : RawData.Length = {0}, HasPrivateKey = {1}, certBytes.Length = {2}", certB.RawData.Length, certB.HasPrivateKey, certBytes.Length );
var keyIdentifier = ( new X509SecurityToken( orig ) ).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>();
certBytes = keyIdentifier.GetX509RawData();
var certC = new X509Certificate2( certBytes );
Console.WriteLine( "cert C : RawData.Length = {0}, HasPrivateKey = {1}, certBytes.Length = {2}", certC.RawData.Length, certC.HasPrivateKey, certBytes.Length );
Console.WriteLine( "RawData equals original RawData: {0}", certC.RawData.SequenceEqual( orig.RawData ) );
Console.ReadLine();
}
}
```
It outputs the following:
```
Orig : RawData.Length = 1337, HasPrivateKey = True
cert A : RawData.Length = 1337, HasPrivateKey = False, certBytes.Length = 1337
cert B : RawData.Length = 1337, HasPrivateKey = True, certBytes.Length = 3187
cert C : RawData.Length = 1337, HasPrivateKey = False, certBytes.Length = 1337
RawData equals original RawData: True
``` | Exporting X.509 certificate WITHOUT private key | [
"",
"c#",
".net",
"ssl-certificate",
"x509certificate2",
""
] |
I have a SELECT element in which I need to auto-select the appropriate option based on the first half of a postcode entered in a text field. British postcodes are of the form *AB12 3CD*, where the first section consists of 1-2 letters representing the county and a number representing the area within the county. The last 3 characters are irrelevant for this question.
For most of the fields it is based on only the first letter(s), but for some options it is a postcode range. The HTML should explain it best:
```
<select id="country_field">
<option value="">Select</option>
<option value="AB">AB (Aberdeen)</option>
<option value="AL">AL (St. Albans)</option>
<option value="B">B (Birmingham)</option>
<option value="BA">BA (Bath)</option>
...
<option value="DD1">DD 1-7 (Dundee)</option>
<option value="DD8">DD 8-11 (Dundee)</option>
...
</select>
```
My code below will currently select the correct element when the value is exactly two letters. But I need to expand it to encompass the single-letter codes (Birmingham) and the postcode ranges (Dundee). Note: I can change the option values if there is a solution that warrants special values, e.g. DD1/DD2 instead of DD1/DD8.
In short:
* B2 --> Birmingham
* BA3 --> Bath
* DD5 --> first Dundee [DD1]
* DD11 --> second Dundee [DD8]
Here's the Javascript I have so far...
```
window.onload = function()
{
// postcode INPUT field
var zipInput = document.getElementById( 'zip_field' );
// county SELECT field
var ctySelect = document.getElementById( 'county_field' );
zipInput.onchange = function()
{
var zipValue = zipInput.value;
var ctyOptions = ctySelect.options;
for ( i = 0; i < ctyOptions.length; i++ )
{
if ( zipValue.substring(0,2) == ctyOptions[i].value )
ctyOptions[i].selected = true;
}
}
}
``` | You can use a regular expression to pull out the values...
```
/^([a-z]{1,2})(\d*)\s/i
```
Then, for a code with a range like DD, perhaps something like this (pseudo-code)...
```
if(match[1].value == "DD") { // needs special processing
range = match[2].value;
range = range < 8 ? 1 : 8; // if the number is less than 8, set it to 1, otherwise set it to 8
listValue = match[1].value + range
} else // just use the letters to select the list item
listValue = match[1].value;
```
So, for `DD5`, this will return `DD1` and for `DD11` it will return `DD8`. Something like `B2` or `BA3` will simply return `B` and `BA`, respectively.
You could change the `if` to a `switch` if you have multiple other codes with different ranges. Then, just set the list item with that value as the current selection. | Replace:
```
zipInput.onchange = function()
{
var zipValue = zipInput.value;
var ctyOptions = ctySelect.options;
for ( i = 0; i < ctyOptions.length; i++ )
{
if ( zipValue.substring(0,2) == ctyOptions[i].value )
ctyOptions[i].selected = true;
}
}
```
With:
```
zipInput.onchange = function()
{
var zipValue = zipInput.value.match(/^[a-z]+/gi);
var ctyOptions = ctySelect.options;
for ( i = 0; i < ctyOptions.length; i++ )
{
if (zipValue[0] === ctyOptions[i].value )
ctyOptions[i].selected = true;
}
}
```
1. First of all, we removeed the variable assign action from the loop. Why waste cycles repeating the same operation?
2. Number two, we now filter out everything except the letters in the beginning of the input.
3. This can in turn be expanded to include the number suffixes, etc. | Auto-selection of <option> based on input field, with some caveats | [
"",
"javascript",
"regex",
"html-select",
"postal-code",
""
] |
I want a certain action to happen when a user has visited X pages of a site
Do I have to store the counter externally (in a txt file or db)?
I can't think of a way to set the counter to 0, then increment it each page load. The counter would always get reset to 0, or am I missing something obvious? | It would be pretty simple to just use `$_SESSION` data to store how many pages an individual has viewed.
```
$_SESSION['pageviews'] = ($_SESSION['pageviews']) ? $_SESSION['pageviews'] + 1 : 1;
``` | The simplest method would be to use PHP's [session storage](http://php.net/session_start#function.session-start.examples).
```
session_start();
@$_SESSION['pagecount']++;
```
PHP automatically sends the user a session cookie, and transparently stores the content of $\_SESSION in a flat file associated with this cookie. You don't really need to roll your own solution for this problem. | How to increment a counter each page load (in PHP)? | [
"",
"php",
"count",
"increment",
""
] |
I have a situation where I would like to be able to rate a users password in the web interface to my system, so that before they hit submit they know if they have a bad password.
Key Requirements:
* Must be able to rate the password, not just pass/fail.
* Should disable the form if the password is below a threshhold, so the user can't submit it.
* Look nice. :)
* Not use jQuery - we're currently using Mochikit and Y!UI in this system.
I've found many password meters written in jQuery, and things like <http://www.passwordmeter.com/> that are too verbose.
Can anyone suggest a good drop in javascript password rater I can use, or give an example of how to write one? | Here's a collection of scripts:
<http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/>
[(archived link)](https://web.archive.org/web/20200812221239/http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/)
I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form? | **Update**: created a js fiddle here to see it live: <http://jsfiddle.net/HFMvX/>
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
```
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
```
Good passwords start to score around 60 or so, here's function to translate that in words:
```
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
```
you might want to tune this a bit but i found it working for me nicely | Password Strength Meter | [
"",
"javascript",
"passwords",
""
] |
How to make security authentication for a web application that is using servlets and .jsp.
I want to make authentication using tomcat.
Can anyone explain steps I need to take in servlet and jsp for FORM authentication.
Servlet is taking care of .jsp page that needs to be secured. | Refer to the [Tomcat Realm Configuration](http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html). | You can also see Chapter 32 of the [J2EE Tutorial](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/) - though that will deal with generic configuration of a servlet based web app. | Servlet security authentication | [
"",
"java",
"security",
"authentication",
"tomcat",
"servlets",
""
] |
I am working on optimizing my site, and I have had the MySQL slow queries log on for a few days now, but after going through >260M queries, it only logged 6 slow queries, and those were special ones executed by me on phpMyAdmin. I am wondering if there is something to log slow PHP page execution time so that I can find certain pages that are hogging resources, rather than specific queries. | First, there is [xdebug](http://www.xdebug.org/), which has a profiler, but I wouldn't use that on a production machine, since it injects code and brings the speed to a crawl. Very good for testing environments, though.
If you want to measure speeds on a productive environment, I would just to the measuring manually. [`microtime()`](http://de.php.net/manual/en/function.microtime.php) is the function for these things in PHP. Assuming you have a header.php and a footer.php which get called by *all* php scripts:
```
# In your header.php (or tpl)
$GLOBALS['_execution_start'] = microtime(true);
# In your footer.php (or tpl)
file_put_contents(
'/tmp/my_profiling_results.txt',
microtime(true) - $GLOBALS['_execution_start'] . ':' . print_r($_SERVER, true) . "\n",
FILE_APPEND
);
``` | what about auto\_prepend\_file and auto\_append\_file,
just wrote a post about it <http://blog.xrado.si/post/php-slow-log> | PHP equivalent to MySQL's slow query log? | [
"",
"php",
"mysql",
"optimization",
""
] |
Until the cross-site XHR API becomes widely supported, what is the best way to make a cross-site request through JavaScript? I've been using iFrames, but those can get a bit messy. Is there a better way? (By better, I mean easier to work with.)
Also, I'd prefer to see pure JavaScript code, not a framework such as jQuery, etc. I'm using my own mini-framework and I don't want to have to look up how they did it.
**EDIT:** I forgot to mention, I have no control over the target server, so I can't use the dynamic `<script>` tags method. | There are 2 common ways I know of. One is using a proxy on your server, basically a php file fetching the data for you.
The other is using dynamic script tags. More info here:
<http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS>
Page 9 of this slideshow also has some info:
<http://bulletproofajax.com/workshop/slides/04formats.html> | You could also take a look at easyxss (<http://code.google.com/p/easyxss/wiki/InvokingRemoteMethods>) . With only a few lines of code you can get method calls that work across the domain-boundry. | Best way to make a cross-site request with JavaScript? | [
"",
"javascript",
"ajax",
"cross-domain",
""
] |
What is the exact difference between these two interfaces? Does [`Enumeration`](http://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html) have benefits over using [`Iterator`](http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html)? If anyone could elaborate, a reference article would be appreciated. | Looking at the Java API Specification for the [`Iterator`](http://java.sun.com/javase/6/docs/api/java/util/Iterator.html) interface, there is an explanation of the differences between [`Enumeration`](http://java.sun.com/javase/6/docs/api/java/util/Enumeration.html):
> Iterators differ from
> enumerations in two ways:
>
> * Iterators allow the caller to remove elements from the underlying
> collection during the iteration with
> well-defined semantics.
> * Method names have been improved.
The bottom line is, both `Enumeration` and `Iterator` will give successive elements, but `Iterator` improved the method names by shortening away the verbiage, and it has an additional `remove` method. Here is a side-by-side comparison:
```
Enumeration Iterator
---------------- ----------------
hasMoreElements() hasNext()
nextElement() next()
N/A remove()
```
As also mentioned in the Java API Specifications, for newer programs, `Iterator` should be preferred over `Enumeration`, as "Iterator takes the place of Enumeration in the Java collections framework." (From the [`Iterator`](http://java.sun.com/javase/6/docs/api/java/util/Iterator.html) specifications.) | Iterators are **fail-fast** . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using `hasNext() or next()` method, the iterator fails quickly by throwing `ConcurrentModificationException` . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the `nextElement()` method that locks the current Vector object which costs lots of time. | Difference between Java Enumeration and Iterator | [
"",
"java",
"collections",
"iterator",
"enumeration",
""
] |
Typically we use WebLogic or JBoss to deploy our apps. I understand that when using open source solutions like Spring you can develop your app and run it on a simple servlet container like Jetty. So the question would be why even bother with an app server? | * Advanced features - like
transactions, security integration, pooling, hi-perf queuing, clusters.
* Performance (weblogic has a hot JVM)
* operational and
administrative interfaces.
beyond that... I don't know?
In most cases, [YAGNI](http://en.wikipedia.org/wiki/YAGNI). | No one got fired for using WebLogic or WebSphere in an enterprise environment. For big businesses and managers not only the technological aspects are important. These application servers offer fully featured administration consoles that are easy to be used even from inexperienced administrators. Also, support services are easier to be found. A company that uses open source components needs to invest on experienced developers to set everything up and do the maintenance. Application servers are widely used within companies (banks for example) that their businesses have nothing to do with software. For them it makes greater sense to buy everything (software license, installation/configuration, support services) from a single vendor. | Application server - to use or not use? | [
"",
"java",
"jakarta-ee",
"jetty",
"application-server",
""
] |
Can anybody explain why do you need to return a reference while overloading operators
e.g.
```
friend std::ostream& operator<< (std::ostream& out, const std::string& str)
``` | It is to make "chaining" of the operator work, in examples like this:
```
std::cout << "hello," << " world";
```
If the first (leftmost) use of the `operator<<()` hadn't returned a reference, there would not be an object to call for the second use of the operator. | It's for operator chaining (if you return a pointer, you have to dereference it) and for not make a potentially huge and expensive copy of an object (in the case you return a value), if it is even possible to do so. | What is the importance of returning reference in operator overloading | [
"",
"c++",
""
] |
I am having trouble figuring out `mem_fun_ref`. I have to admit, I usually use functors for this kind of thing, since they can be inlined for speed and profit. However, this code is not going to be a bottleneck and so I wanted to try this thing.
Here is an example of what I want to do. I know there are other ways to do it. I don't want to use `copy`, I don't want to use range member functions, I don't want to use a `back_inserter`. I specifically want to use `mem_fun_ref`. This is just a simple example, the real case is much more complicated. That said, I really don't know why this is wrong, but I am not familiar with `mem_fun_ref` or `mem_fun`.
Here's what I want to work:
```
#include <list>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
list<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
vector<int> b;
// should work like magic!
for_each(a.begin(), a.end(), bind1st(mem_fun_ref(&vector<int>::push_back), b));
}
```
But I get 3 errors:
```
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(276) : error C2529: '_Right' : reference to reference is illegal
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(281) : error C2529: '_Right' : reference to reference is illegal
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(282) : error C2535: 'void std::binder1st<_Fn2>::operator ()(const int &(&)) const' : member function already defined or declared
1> with
1> [
1> _Fn2=std::mem_fun1_ref_t<void,std::vector<int>,const int &>
1> ]
1> c:\program files\microsoft visual studio 9.0\vc\include\functional(276) : see declaration of 'std::binder1st<_Fn2>::operator ()'
1> with
1> [
1> _Fn2=std::mem_fun1_ref_t<void,std::vector<int>,const int &>
1> ]
```
`reference to reference is illegal` makes me think that the function needs to take a parameter by value. But of course, this is not possible to change in `vector`, and it's not possible to change it in my code either. Is there a simple change to get this to work? I need a solution that's a 1-liner. | Just use `bind`. The `mem_fun` versions are too difficult.
```
for_each(a.begin(), a.end(),
boost::bind(&vector<int>::push_back, boost::ref(b), _1));
```
Another way that doesn't require the use of `ref` is to pass a pointer to the vector to be modified:
```
for_each(a.begin(), a.end(),
boost::bind(&vector<int>::push_back, &b, _1));
``` | This problem was explained in "Exceptional C++ Style" by Herb Sutter, page 28-30. One probably cannot safely create a pointer to a `vector<int>::push_back` method as one needs to be sure of exact signature of the member function, which may not be obvious even for `vector<int>::push_back` in Standard Library. This is because (in Standard Library):
1. A member function signature with default parameters might be replaced by "two or more member function signatures with equivalent behavior.
2. A member function signature might have additional defaulted parameters.
In the end, Herb Sutter advised that
1. Use mem\_fun, Just Not with the Standard Library
2. Use Pointers to Member Functions, Just Not with the Standard Library | mem_fun_ref trouble | [
"",
"c++",
"stl",
"function-pointers",
""
] |
Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python?
```
old_list = []
old_list = list()
```
The reason I ask is that I just saw this in some running code:
```
del old_list[ 0:len(old_list) ]
``` | Clearing a list in place will affect all other references of the same list.
For example, this method doesn't affect other references:
```
>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]
```
But this one does:
```
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:] # equivalent to del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True
```
You could also do:
```
>>> a[:] = []
``` | Doing `alist = []` does not clear the list, just creates an empty list and binds it to the variable `alist`. The old list will still exist if it had other variable bindings.
To actually clear a list *in-place*, you can use any of these ways:
1. `alist.clear() # Python 3.3+, most obvious`
2. `del alist[:]`
3. `alist[:] = []`
4. `alist *= 0 # fastest`
See the [Mutable Sequence Types](https://docs.python.org/dev/library/stdtypes.html#typesseq-mutable) documentation page for more details. | Different ways of clearing lists | [
"",
"python",
"list",
""
] |
What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them? | Pointers are best understood by C & C++'s differences in variable passing to functions.
Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively).
But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array? Passing it by value would be foolish: why would you copy 20 megs for this operation, and if you end up modifying it (i.e. it's an out-parameter) you have to copy that 20 megs BACK?
Better is to just "point" to it. You say, "here's a pointer to a big blob of memory". And that little indirection saves a ton of time.
Once you understand that, everything else is basically the same. Rearranging items in a list becomes just swapping pointers rather than copying every item around, you don't need to know how big things are when you start out, etc | Pointers are most useful when dealing with data structures whose size and shape are not known at compile-time (think lists, trees, graphs, arrays, strings, ...).
**Edit**
These related answers might also help (the top answer in the second link is definitely worth a look):
[In C++ I Cannot Grasp Pointers and Classes](https://stackoverflow.com/questions/96285/in-c-i-cannot-grasp-pointers-and-classes)
[What are the barriers to understanding pointers and what can be done to overcome them?](https://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome) | What is the point of pointers? | [
"",
"c++",
"pointers",
""
] |
I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.
I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way.
### Similar question:
* [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473) | You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):
```
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
// (we use slice to clone the array so the
// original array won't be modified)
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
```
In case, if you are to return as a function for duplicates. This is for similar type of case.
Reference: <https://stackoverflow.com/a/57532964/8119511> | If you want to elimate the duplicates, try this great solution:
```
function eliminateDuplicates(arr) {
var i,
len = arr.length,
out = [],
obj = {};
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
}
console.log(eliminateDuplicates([1,6,7,3,6,8,1,3,4,5,1,7,2,6]))
```
Source:
<http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/> | Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array | [
"",
"javascript",
"arrays",
""
] |
What's the preferred method to use to change the location of the current web page using JavaScript? I've seen both window.navigate and document.location used. Are there any differences in behavior? Are there differences in browser implementations? | ```
window.location.href = 'URL';
```
is the standard implementation for changing the current window's location. | > window.navigate not supported in some browser
>
> In java script many ways are there for redirection, see the below code
> and explanation
```
window.location.href = "http://krishna.developerstips.com/";
window.location = "http://developerstips.com/";
window.location.replace("http://developerstips.com/");
window.location.assign("http://work.developerstips.com/");
```
> **window.location.href** loads page from browser's cache and does not
> always send the request to the server. So, if you have an old version
> of the page available in the cache then it will redirect to there
> instead of loading a fresh page from the server.
>
> **window.location.assign()** method for redirection if you want to allow
> the user to use the back button to go back to the original document.
>
> **window.location.replace()** method if you want to want to redirect to a
> new page and don't allow the user to navigate to the original page
> using the back button. | Should I use window.navigate or document.location in JavaScript? | [
"",
"javascript",
"html",
"navigation",
""
] |
What is the best way to carry an auto incremented ID from one form to another?
I have 3 tables (users, residences, and users\_residences). I want a user to register, be added to the users table, be redirected to a form to create a residence which will add a row to the residence table and simultaneously add the the residence tabe row's id and the users table row's id to the users\_residences table.
I have been playing around with uri segments but can't think of a way to store (or call) the just added user's ID for use in the second form.
I could probably use sessions to store an session id in the users table, then find the row ID from that, but it seems pretty hacky.
I am quite new to programming so feel free to tell me that I fail, but at least point me in the direction of where I can learn some of these concepts.
Thanks
Al | I'd say you are better off with the session key in the users table; it's more secure (assuming you are doing this over https).
Storing a value in a hidden field is easy to manipulate from a security perspective. If your fields use auto increment, It's also easy to guess what the next one will be. A user could just pretend to be the next user registering and take that user's info. You are also giving info about what other user's ids are, how many users are registered for your site, etc.
Also, unless you are planning on doing something ajaxy, I'm not sure there is much of a choice; the user would click submit, get redirected to another webpage while the save is happening, the only information that could be transmitted would be url you redirect them to or session. You could pass it in the url, but it would also have the above problems. | In the second form you could include:
```
<input type='hidden' name='user_id' value='whatever' />
``` | Carrying row values from MYSQL after form submission | [
"",
"php",
"mysql",
"codeigniter",
""
] |
I'm trying to run a command-line program and piping in a file. The command works fine on the command-line, but I can't seem to get it to work with the Process object in C#. Here's the command I'm issuing:
"C:\Servers\CollabNet Subversion Server\svnadmin" load C:\Repositories\TestLoad < C:\Temp\test.dump
This function works fine with all the other commands that I pass to it, except for the command above:
```
public static bool ExecuteSvnCommand( string command, string arguments, out string result, out string errors )
{
bool retval = false;
string output = string.Empty;
string errorLines = string.Empty;
Process svnCommand = null;
var psi = new ProcessStartInfo( command );
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
try
{
Process.Start( psi );
psi.Arguments = arguments;
svnCommand = Process.Start( psi );
StreamReader myOutput = svnCommand.StandardOutput;
StreamReader myErrors = svnCommand.StandardError;
svnCommand.WaitForExit();
if ( svnCommand.HasExited )
{
output = myOutput.ReadToEnd();
errorLines = myErrors.ReadToEnd();
}
// Check for errors
if ( errorLines.Trim().Length == 0 )
{
retval = true;
}
}
catch ( Exception ex )
{
string msg = ex.Message;
errorLines += Environment.NewLine + msg;
}
finally
{
if (svnCommand != null)
{
svnCommand.Close();
}
}
result = output;
errors = errorLines;
return retval;
}
```
I've tried several different combinations of this function, but I can't get this to work. I keep getting a "The system cannot find the file specified" message. I've been at this for about a week now, and I think I need a few set of eyes to see what I'm doing wrong. | Both Mark and Luke gave me the right direction to go. I couldn't use either answer because I had to do this so that it could run with Mono in Linux. So I ended up writing to the StandardInput as suggested. Here is the code that works:
```
public static bool ExecuteSvnCommandWithFileInput( string command, string arguments, string filePath, out string result, out string errors )
{
bool retval = false;
string output = string.Empty;
string errorLines = string.Empty;
Process svnCommand = null;
var psi = new ProcessStartInfo( command );
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
try
{
Process.Start( psi );
psi.Arguments = arguments;
svnCommand = Process.Start( psi );
var file = new FileInfo(filePath);
StreamReader reader = file.OpenText();
string fileContents = reader.ReadToEnd();
reader.Close();
StreamWriter myWriter = svnCommand.StandardInput;
StreamReader myOutput = svnCommand.StandardOutput;
StreamReader myErrors = svnCommand.StandardError;
myWriter.AutoFlush = true;
myWriter.Write(fileContents);
myWriter.Close();
output = myOutput.ReadToEnd();
errorLines = myErrors.ReadToEnd();
// Check for errors
if ( errorLines.Trim().Length == 0 )
{
retval = true;
}
}
catch ( Exception ex )
{
string msg = ex.Message;
errorLines += Environment.NewLine + msg;
}
finally
{
if (svnCommand != null)
{
svnCommand.Close();
}
}
result = output;
errors = errorLines;
return retval;
}
``` | I'm not 100% sure but my guess would be that you have to manually push the data from `test.dump` to the process using its `StandardInput` property.
Otherwise you could try using `cmd.exe` to execute the command:
```
var psi = new ProcessStartInfo( "cmd.exe /c \"" + command "\"" );
```
The reason for this is that the ">", "<" and "|" operators are implemented by the shell itself (cmd.exe). | Piping in a file on the command-line using System.Diagnostics.Process | [
"",
"c#",
"command-line",
""
] |
I'm using jQuery and I have a function that serves as an event callback, and so in that function "this" represents the object that that captured the event. However, there's an instance where I want to call the function explicitly from another function - how do I set what "this" will equal within the function in this case?
For example:
```
function handleEvent(event) {
$(this).removeClass("sad").addClass("happy");
}
$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
handleEvent(e); // in this case, "this" will be the window object
// but I'd like to set it to be, say, the input in question
}
}
``` | Use ~~[apply](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply)~~ [call](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call).
```
handleEvent.call(this, e);
``` | Just parameterize the function you're interested in:
```
function doStuff(el) {
$(el).removeClass("sad").addClass("happy");
}
function handleEvent(event) {
doStuff(this);
}
$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked
function differentEvent(event) {
$("input.sad").keydown(e) {
doSomeOtherProcessing();
doStuff(this);
}
}
``` | When calling a Javascript function, how do I set a custom value of "this"? | [
"",
"javascript",
"jquery",
"this",
"jquery-events",
""
] |
I have a web app where I am calling a SELECT DISTINCT query on two joined tables. If I try to run the query from the web page, I get the following error: "The text, ntext, or image data type cannot be selected as DISTINCT". When I run it from within SQL Management Studio, the query runs fine - no error. Even more interestingly, there are no text, ntext, or image data types in either of the tables.
It should be noted that I'm stepping through the code, and right before the query is executed, I'm copying the query from the "watch" window into Mgmt Studio, and it runs, when I step through and let .NET run it, the error is thrown. I'm using .NET 2, and the System.Data.SqlClient namespace.
Here is my query:
```
SELECT DISTINCT ResponseFormParent.*
FROM ResponseFormParent
INNER JOIN ResponseForm
ON ResponseFormParent.ResponseFormParentId = ResponseForm.ResponseFormParentId
WHERE ResponseForm.RegistrationDeadline >= '5/1/2009'
```
ResponseFormParent has 3 ints, 1 datetime, and 1 nvarchar(50).
ResponseForm has 4 ints, 1 datetime, 1 bit, and 1 nvarchar(255).
What is causing the problem? The error doesn't make sense.
---
UPDATE: code to call query
```
public DataSet ExecuteQuery(string sql)
{
DataSet ds = null;
try
{
using (SqlConnection dbconn = new SqlConnection(connectionString))
using (SqlCommand dbcmd = new SqlCommand(sql, dbconn))
{
SqlDataAdapter dbadapter = new SqlDataAdapter(dbcmd);
ds = new DataSet();
dbadapter.Fill(ds);
}
}
catch (Exception ex)
{
Utility.LogError(sql, ex);
}
return ds;
}
``` | Just tested a DISTINCT query on a table that contains an ntext column. It works as long as you avoid selecting the ntext column. When you include the ntext column, you get the error you name.
So are you sure your code is doing:
```
SELECT DISTINCT ResponseFormParent.*
```
And not
```
SELECT DISTINCT *
``` | You might be querying two different databases. Have you checked your Connection in your app to make sure you're actually querying the same database that you're querying against in SQL Mgmt Studio? It's also possible that you're pointing to different servers. You might want to check that in your Connection as well.
If either is the case, then it's most likely a database schema mismatch between the two databases you're querying against. | SELECT DISTINCT not working in .NET application, but works in SQL Mgmt Studio | [
"",
".net",
"sql",
"t-sql",
"sql-server-2000",
""
] |
so i am building a client server application and i have to chose how they are going to talk to each other. i can:
1. have a TCP connection between client and server
2. send messages over REST or SOAP
3. using Tibco RV, EMS or IBM MQ . .
is there a matrix anywhere that can show me where i would use one of these technologies versus another. stuff like performance, reliability, etc would be helpfu. | Go for WCF if you have a pure .NET to .NET application. It will make your life simple when it comes to doing TCP/IP but preserving a nice layer of object oriented design to your messaging. It also makes it insanely easy to unit test your messaging code, which is I think the biggest benefit.
WCF will do TCP/IP, pipes on the local machine and it also supports many HTTP based solutions. You also get security for free on most of it and the code does a lot of error handling in the communication layers for you.
If you need an MQ solution, then have fun though. MSMQ is supported, but then again it's also MSMQ.
Using other solutions will benefit from more features, but with features comes complexity and risk. I've personally integrated a .Net application with websphere MQ and I was unimpressed with the cost and benefits of the solution. Not to mention that the performance of MQ on non P-Series hardware is lacking to say the least. | **Queued or not queued?**
What do you need from your messaging solution?
1. **Interoperability**? Do you need to be able to expose your solution to other applications? Then you'll need to go with one of the formats and protocols supported out there and that 99% of the cases means REST or SOAP
2. **Availability**? Does your client needs to be able to send message even when the server is down, unavailable or going through maintenance, then you'll certainly need a queued solution (MSMQ, MQ, SSB)
3. **Security**? Do the client and server need to authenticate across domains of trust? Then you need to make sure your solution has a non-domain based story for authentication (eg. certificates).
4. **Reliability**? If you client crashes, does it needs to resume sending pending messages? Again, only a queued solution will help here.
5. **Correlation**? Do you need to process correlated messages in order, do you need exclusive access to correlated messages, do you need to send back replies? Not all solutions offer a session semantics.
6. **Scalability**? Do you need to support one client or one million? Again, only a queued solution will work after a certain scale.
7. **Spikes**? Does your traffic has any spikes, like certain hours or days when it surges up? A coupled solution has to be planned for the capacity to accept the highest spike it can encounter or it will unceremoniously reject clients. If your hardware cannot cope with your regular spikes then you'll have to use a queued solution.
If [you like WCF](http://en.wikipedia.org/wiki/Drinking_the_Kool-Aid) then you going to get a lot for free from it. But basically there are two modes of doing messaging: queued and non-queued. WCF offers a huge matrix of interchangeable channels, bindings, formats, protocols and authentication methods that can be switched in and out at a simple change of the .config file. But they're all for the **non queued** mode. If your solution is OK with a coupled communication channel then probably there's nothing better than WCF at the moment for CLR applications. If your requirements impose a queued based solution then you'll loose all the cool interchangeable binding toys and you'll leverage from WCF the serialization and maybe the activation model of your service.
And last but not least 90% of the messages sent in any messaging solutions end up in a database and quite a few also originate from a database. If you want a tight integration with SQL Server databases that offers performance while guaranteeing reliable delivery, there [is a solution for that in SSB](http://msdn.microsoft.com/en-us/library/bb522893.aspx). | Choosing a messaging solution | [
"",
"c#",
"messaging",
""
] |
I play the online game World of Warcraft, which is plagued by automated bots that inspect the game's allocated memory in order to read game/player/world state information, which is used to mechanically play the game. They also sometimes write directly to the game's memory itself but the more sophisticated ones don't, as far as I know.
The game's vendor, Blizzard Entertainment, has a separate application called Warden that it is supposed to detect and disable hacks and cheats like that, but it doesn't catch everything.
Would it be possible to make a Windows application where you're the only one that can read the things you've read into memory?
Would that be pragmatic to implement on a large C++ application that runs on millions of machines? | Can't be done. The application is at the mercy of the OS when it comes to memory access. Whoever controls the OS controls access to memory. A user has full access to the whole machine, so they can always starts processes with privileges set to allow them to read from other processes' memory space.
This is assuming a 'regular' environment - today's hardware, with a multipurpose OS that allows several simultaneous programs to run, etc.
Think of it this way - even single-purpose machines where developers have full control over the hardware, with digital signing and all the tricks possible like the XBox or PlayStation can't manage to keep third-party code out. For a multi-purpose OS, it'd be 10 times harder. | If you want to achieve a real security, not only obscurity, this needs to be done at operating system level. This is a part of what is called [Trusted Computing](http://en.wikipedia.org/wiki/Trusted_Computing#Preventing_cheating_in_online_games), something which was talked about a lot in the past years but no real progress was made (you can search for Microsoft Palladium for one example).
If you try to look at this a a cryptographic problem with a private and public keys, currently there is no way to hide a private key you use in your application from the hacker. Once the hacker finds your private key, he can use it to emulate your application - and all you can do is to make this somewhat harder.
Some partial solutions are possible in multiplayer games, where part of the game is run on servers. You can use the fact the hacker does not have an access to the server and therefore server can perform operations using its own private key which hacker is unable to get. This can help is some situations, but it far from being a general solution. | Cheating in online games: Is it possible to prevent one Win32 process from inspecting/manipulating another's memory? | [
"",
"c++",
"security",
"winapi",
""
] |
I'm trying to insert a clob into Oracle. If I try this with an OdbcConnection it does not insert the data into the database. It returns 1 row affected and no errors but nothing is inserted into the database.
It does work with an OracleConnection. However, using the Microsoft OracleClient makes our webservices often crash with an AccessViolationException (Attempted to read or write protected memory. This is often an indication that other memory is corrupt.). This happens a lot when we use OracleDataAdapter.Fill(dataset). So using this doesn't seem like an option.
Is there any way to insert/update clobs with more then 4.000 characters from .Net with an OdbcConnection? | I haven't worked on the .NET platform in awhile, so this is from memory.
To the best of my knowledge, OdbcConnection's adapter for Oracle is ancient and you cannot insert/update more than 4,000 characters at a time. You can write a stored procedure to transfer and update the CLOB 4,000 characters at a time, but that seems like a arduous and inefficient means to support an aging library.
So, MS's OracleConnection may be a better path to debug. AccessViolationException is most often cause by the Distributed Transaction Controller (msdtc.exe) not being started, though there are numerous other potential causes (including faulty hardware).
Before you investigate the exception, there is a third connection library to consider. Oracle's DataAccess Components (ODAC ODP.NET), which should be included with your database license. It's much better supported than OdbcConnection and should bypass OracleConnection's exception throwing. | I don't think this is a problem with odbc but rather a limitation on oracles part. If you are inserting or updating using a select statement you cannot use more that 4000 chars. The recommended way to do this is using bind variables and plsql. I know this sounds like a very ugly solution but it is all I have found so far ;(.
<http://www.evilcyborg.com/lounge/?ID=1245> | Inserting clobs into oracle with ODBC | [
"",
"c#",
"oracle",
"odbc",
"clob",
""
] |
I have a template string and an array of parameters that come from different sources but need to be matched up to create a new "filled-in" string:
```
string templateString = GetTemplate(); // e.g. "Mr {0} has a {1}"
string[] dataItems = GetDataItems(); // e.g. ["Jones", "ceiling cat"}
string resultingString = String.Format(templateString, dataItems);
// e.g. "Mr Jones has a ceiling cat"
```
With this code, I'm assuming that the number of string format placeholders in the template will equal the number of data items. It's generally a fair assumption in my case, but I want to be able to produce a `resultingString` without failing even if the assumption is wrong. I don't mind if there are empty spaces for missing data.
If there are too many items in `dataItems`, the `String.Format` method handles it fine. If there aren't enough, I get an Exception.
To overcome this, I'm counting the number of placeholders and adding new items to the dataItems array if there aren't enough.
To count the placeholders, the code I'm working with at the moment is:
```
private static int CountOccurrences(string haystack)
{
// Loop through all instances of the string "}".
int count = 0;
int i = 0;
while ((i = text.IndexOf("}", i)) != -1)
{
i++;
count++;
}
return count;
}
```
Obviously this makes the assumption that there aren't any closing curly braces that aren't being used for format placeholders. It also just *feels* wrong. :)
**Is there a better way to count the string format placeholders in a string?**
---
A number of people have correctly pointed out that the answer I marked as correct won't work in many circumstances. The main reasons are:
* Regexes that count the number of placeholders doesn't account for literal braces ( `{{0}}` )
* Counting placeholders doesn't account for repeated or skipped placeholders (e.g. `"{0} has a {1} which also has a {1}"`) | Merging Damovisa's and Joe's answers.
I've updated answer afer Aydsman's nad activa's comments.
```
int count = Regex.Matches(templateString, @"(?<!\{)\{([0-9]+).*?\}(?!})") //select all placeholders - placeholder ID as separate group
.Cast<Match>() // cast MatchCollection to IEnumerable<Match>, so we can use Linq
.Max(m => int.Parse(m.Groups[1].Value)) + 1; // select maximum value of first group (it's a placegolder ID) converted to int
```
This approach will work for templates like:
"{0} aa {2} bb {1}" => count = 3
"{4} aa {0} bb {0}, {0}" => count = 5
"{0} {3} , {{7}}" => count = 4 | Counting the placeholders doesn't help - consider the following cases:
"{0} ... {1} ... {0}" - needs 2 values
"{1} {3}" - needs 4 values of which two are ignored
The second example isn't farfetched.
For example, you may have something like this in US English:
```
String.Format("{0} {1} {2} has a {3}", firstName, middleName, lastName, animal);
```
In some cultures, the middle name may not be used and you may have:
```
String.Format("{0} {2} ... {3}", firstName, middleName, lastName, animal);
```
If you want to do this, you need to look for the format specifiers **{index[,length][:formatString]}** with the maximum index, ignoring repeated braces (e.g. {{n}}). Repeated braces are used to insert braces as literals in the output string. I'll leave the coding as an exercise :) - but I don't think it can or should be done with Regex in the most general case (i.e. with length and/or formatString).
And even if you aren't using length or formatString today, a future developer may think it's an innocuous change to add one - it would be a shame for this to break your code.
I would try to mimic the code in StringBuilder.AppendFormat (which is called by String.Format) even though it's a bit ugly - use Lutz Reflector to get this code. Basically iterate through the string looking for format specifiers, and get the value of the index for each specifier. | Is there a better way to count string format placeholders in a string in C#? | [
"",
"c#",
".net",
"string",
""
] |
I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error:
> "File in use by another process"
I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling. This is against my religion, so I was wondering if anyone has a better way of doing it? | **Updated NOTE on this solution**: Checking with `FileAccess.ReadWrite` will fail for Read-Only files so the solution has been modified to check with `FileAccess.Read`.
**ORIGINAL:**
I've used this code for the past several years, and I haven't had any issues with it.
Understand your hesitation about using exceptions, but you can't avoid them all of the time:
```
protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
//file is not locked
return false;
}
``` | You can suffer from a thread race condition on this which there are documented examples of this being used as a security vulnerability. If you check that the file is available, but then try and use it you could throw at that point, which a malicious user could use to force and exploit in your code.
Your best bet is a try catch / finally which tries to get the file handle.
```
try
{
using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))
{
// File/Stream manipulating code here
}
} catch {
//check here why it failed and ask user to retry if the file is in use.
}
``` | Is there a way to check if a file is in use? | [
"",
"c#",
".net",
"file",
"file-io",
"file-locking",
""
] |
I have proprietary application sending out multicast packet to the network. It is running on the linux with NIC MTU 1500.
And then I write a simple java program to using MulticastSocket class to receive message. I found it is DatagramPacket size is ~7900. The receiver program is running on the linux with NIC MTU 1500.
I rewrite the program in C and using recvfrom() call, but the result is the same.
I don't understand why? is it packet size limited by NIC MTU? or can it be override by the program? | Fragmentation and reassembly happen at the IP layer, which is beneath the UDP protocol, so it's essentially hidden from view. You can test for fragmentation by setting the 'do not fragment' flag on varying packet sizes. | I would guess that you are testing on the machine where the proprietary service is running. In that case, the linux box will let them communicate over the local loopback device, which has a MTU of 64k. | RecvFrom() returns packet larger than sender NIC MTU | [
"",
"java",
"linux",
"networking",
""
] |
Consider the following code, I have a textblock that is an "on/off" button in WPF. It's just text inside an ellipse that says ON / OFF. When the user clicks the button and holds the left mouse for ONE second, it will execute the 'turn device on' code if the device is not already powered up. If the user holds the ON/OFF button for three seconds or more (keeps left mouse button HELD down) the device will turn off.
Several problems that I'm missing the boat on.
1. The tick event is not firing while the mouse button is held down, despite the fact the timer is started.
2. The do/while loop never exits despite lifting the button
Thanks!
```
public int TimerCount = 0;
private void ButtonPressTimer(object sender, EventArgs e)
{
TimerCount = TimerCount + 1;
}
private void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var buttonPressTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 1), DispatcherPriority.Normal, ButtonPressTimer, this.Dispatcher);
do
{
if (!buttonPressTimer.IsEnabled)
buttonPressTimer.Start();
}
while (e.ButtonState == MouseButtonState.Pressed);
buttonPressTimer.Stop();
if (TimerCount >= 3)
{
//do something here
}
else
{
//do something different here
}
}
``` | I'd look at a slightly different approach that doesn't require the overhead of setting up a timer. If you handle both the mouse down and up events, and store the time when the button was pressed, you can compare it to the time when the mouse is released and decide what to do.
```
private DateTime mousePressed;
private void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mousePressed = DateTime.Now;
}
private void txtBlockOnOff_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// button released
TimeSpan difference = DateTime.Now - mousePressed;
if (difference.TotalSeconds >= 3)
{
// long press
}
else
{
// short press
}
}
``` | I believe the answer to this question is to use the RepeatButton which does exactly what you require, i.e. it continues to fire the event until you let the button up. | WPF DispatcherTimer and Mouse Button Click Timing | [
"",
"c#",
".net",
"wpf",
""
] |
I have a situation where I am running multiple instances of my WPF application. I want the instances to share the same user.config file. Currently, whichever instance writes to the user.config file last wins. I'd prefer for all the instances to watch the user.config file and reload the settings whenever another instance changes it. The user.config file is currently located here:
C:\Documents and Settings\*username*\Local Settings\Application Data\*company name*\*ExeName*.exe\_StrongName\_*hash*\1.0.0.0
For example, C:\Documents and Settings\usename\Local Settings\Application Data\Company\5kAdCon.exe\_StrongName\_gxh0g12uyafipnfrslaggvy4vvk01fko\1.0.0.0
**Is there a way for me to get this full path (including the hash) so I can add a file watcher to the user.config file?**
If so, I want to reload the settings when the file changes. Is it as easy as calling this method?
```
Properties.Settings.Default.Reload();
``` | I found it. The following code will return the path to the user.config file. You need to add a reference to System.Configuration.dll
```
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
string path = config.FilePath;
```
Now I can use a [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) to get notified when the file changes. | You should Cache the file and implement CacheDependency so that if any change is made to the file the file gets reloaded in the Cache. I am using a permission xml file in my application which gets stored in the cache and reloaded if file gets changed. Here's the code:
```
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument permissionsDoc = null;
if (Cache["Permissions"] == null)
{
string path = Server.MapPath("~/XML/Permissions.xml");
permissionsDoc = new XmlDocument();
permissionsDoc.Load(Server.MapPath("~/XML/Permissions.xml"));
Cache.Add("Permissions", permissionsDoc,
new CacheDependency(Server.MapPath("~/XML/Permissions.xml")),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default, new CacheItemRemovedCallback(ReloadPermissionsCallBack));
}
else
{
permissionsDoc = (XmlDocument)Cache["Permissions"];
}
}
private void ReloadPermissionsCallBack(string key, object value, CacheItemRemovedReason reason)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/XML/Permissions.xml"));
Cache.Insert("Permissions", doc ,
new CacheDependency(Server.MapPath("~/XML/Permissions.xml")),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default, new CacheItemRemovedCallback(ReloadPermissionsCallBack));
}
```
Caching will also increase your application performance. | How can I watch the user.config file and reload the settings when it changes? | [
"",
"c#",
"wpf",
"settings",
"user-config",
""
] |
When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:
```
@debuggable
def myfunc(argA,argB,argC):
return argB+1
```
and use a global variable to switch on or off debugging. No, you don't like globals either, I guessed.
The best I can come up with is:
```
DEBUG = True
def debuggable(func):
if DEBUG:
def decorated(*args):
print "Entering ",func.func_name
print " args ",args
ret = func(*args)
print ret
return ret
return decorated
else:
return func
@debuggable
def myfunc(this,that):
return this+that
```
And running:
```
>>> myfunc(1,3)
Entering myfunc
args (1, 3)
4
```
How can I improve that? | Use a debugger. Seriously. Decorating every function you want to keep track is a bad idea.
Python [has a debugger included](http://docs.python.org/library/pdb.html), so you don't need a good IDE.
If you don't want to use a debugger, you can use the [trace function](http://docs.python.org/library/sys.html#sys.settrace).
```
import sys
@sys.settrace
def trace_debug(frame, event, arg):
if event == 'call':
print ("calling %r on line %d, vars: %r" %
(frame.f_code.co_name,
frame.f_lineno,
frame.f_locals))
return trace_debug
elif event == "return":
print "returning", arg
def fun1(a, b):
return a + b
print fun1(1, 2)
```
That prints:
```
calling 'fun1' on line 14, vars: {'a': 1, 'b': 2}
returning 3
3
```
Even easier would be to use [Winpdb](http://winpdb.org/):
It is a **platform independent** graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.
Features:
* GPL license. Winpdb is Free Software.
* Compatible with CPython 2.3 or later.
* Compatible with wxPython 2.6 or later.
* Platform independent, and tested on Ubuntu Gutsy and Windows XP.
* User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.
[](https://i.stack.imgur.com/qaXk2.jpg)
(source: [winpdb.org](http://winpdb.org/images/screenshot_winpdb_small.jpg)) | I think what you're after isn't really a debugging decorator, but more of a logging decorator.
It might make sense to use [Python's logging module](http://docs.python.org/library/logging.html) so you can have more fine grained control over the logging itself. For example you would be able to output to a file for later analysing the output.
The decorator might then look something more like:
```
import logging
logger = logging.getLogger('TraceLog')
# TODO configure logger to write to file/stdout etc, it's level etc
def logthis(level):
def _decorator(fn):
def _decorated(*arg,**kwargs):
logger.log(level, "calling '%s'(%r,%r)", fn.func_name, arg, kwargs)
ret=fn(*arg,**kwargs)
logger.log(level, "called '%s'(%r,%r) got return value: %r", fn.func_name, arg, kwargs, ret)
return ret
return _decorated
return _decorator
@logthis(logging.INFO)
def myfunc(this,that):
return this+that
```
Then if you configure the logger to output to stderr you'd see:
```
>>> logger.setLevel(logging.INFO)
>>> handler=logging.StreamHandler()
>>> logger.addHandler(handler)
>>> myfunc(1,2)
calling 'myfunc'((1, 2),{})
called 'myfunc'((1, 2),{}) got return value: 3
``` | How would you write a @debuggable decorator in python? | [
"",
"python",
"decorator",
""
] |
I have a class in c++ a portion of which is below
```
class Node{
public:
vector<string> getNames() const;
private:
vector<string> names_;
};
vector<string> Node::getNames(){
return names_;
}
```
the function getNames() passes a copy of the vector. How can i modify my class so that i can reference the vector 'by const reference' from any other class that i declare the Node object instead of passing a copy? | Try this:
```
class Node
{
public:
const vector<string>& getNames() const;
private:
vector<string> names_;
};
const vector<string>& Node::getNames() const
{
return names_;
}
```
Few things:
1. getNames() is now a const method, because the Node does not logically change.
2. Return as a constant reference, so you don't make a copy. | Change the definition to
```
const vector<string>& getNames() const;
``` | access a variable by reference from a class in c++ | [
"",
"c++",
""
] |
i have 10 textboxes and i need to select text from each one of them.
The problem is that i cant select text from multiple textboxes.
Is there any solution for this problem my code is.
```
private void Form1_Load(object sender, EventArgs e)
{
createTextBoxes(10);
((TextBox)textBoxes[0]).Select(1, 4);
((TextBox)textBoxes[1]).Select(1, 4); // <- it will not select text
((TextBox)textBoxes[2]).Select(1, 4); // same here
}
Control[] textBoxes;
private void createTextBoxes(int cnt)
{
textBoxes = new Control[cnt];
for (int i = 0; i < cnt; i++)
{
TextBox tb = new TextBox();
tb.Name = i.ToString();
tb.Location = new Point(5, 5 + 14 * i);
tb.Size = new Size(600, 20);
tb.BorderStyle = BorderStyle.None;
tb.Text = "sample text" + i.ToString();
textBoxes[i] = tb;
this.Controls.Add(tb);
}
}
``` | Set the HideSelection property of the texboxes to false. They will maintain selection after losing focus. | Only one control can have a "Focus" at a time... you can't select (ie:highlight) text of multiple controls.
I also just tested by adding a button to the form and posted your 3 "select" snippets there too... nothing showed highlighted. However, when I did a TAB through each control, the first 3 respectfully showed the highlighted section. When I tabbed through the rest, the entire field of the rest of the textboxes were fully selected.
Or are you really trying to accomplish something else... | Select text from multiple textboxes simultaneously | [
"",
"c#",
"textbox",
""
] |
Does anybody know any good simple youtube search scripts in php that I could use right off the bat? I don't want to use the Zend Framework (not installed), just the basic REST calls.
Thanks | what's wrong with the [official youtube api](https://developers.google.com/youtube/)?
you don't need the whole ZF for that, it should work separatley too. | <http://www.ibm.com/developerworks/xml/library/x-youtubeapi/>
ok | Simple Youtube Search PHP Script | [
"",
"php",
"youtube",
""
] |
I was working on an AJAX-enabled asp.net application.
I've just added some methods to Array.prototype like
```
Array.prototype.doSomething = function(){
...
}
```
This solution worked for me, being possible reuse code in a 'pretty' way.
But when I've tested it working with the entire page, I had problems..
We had some custom ajax extenders, and they started to behave as the unexpected: some controls displayed 'undefined' around its content or value.
What could be the cause for that? Am I missing something about modifing the prototype of standart objects?
Note: I'm pretty sure that the error begins when I modify the prototype for Array. It should be only compatible with IE. | While the potential for clashing with other bits o' code the override a function on a prototype is still a risk, if you want to do this with modern versions of JavaScript, you can use the [`Object.defineProperty`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) method, e.g.
```
// functional sort
Object.defineProperty(Array.prototype, 'sortf', {
value: function(compare) { return [].concat(this).sort(compare); }
});
``` | Modifying the built-in object prototypes is a bad idea in general, because it always has the potential to clash with code from other vendors or libraries that loads on the same page.
In the case of the Array object prototype, it is an especially bad idea, because it has the potential to interfere with any piece of code that iterates over the members of any array, for instance with `for .. in`.
To illustrate using an example (borrowed from [here](https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays/500531#500531)):
```
Array.prototype.foo = 1;
// somewhere deep in other javascript code...
var a = [1,2,3,4,5];
for (x in a){
// Now foo is a part of EVERY array and
// will show up here as a value of 'x'
}
```
Unfortunately, the existence of questionable code that does this has made it necessary to also avoid using plain `for..in` for array iteration, at least if you want maximum portability, just to guard against cases where some other nuisance code has modified the Array prototype. So you really need to do both: you should avoid plain `for..in` in case some n00b has modified the Array prototype, and you should avoid modifying the Array prototype so you don't mess up any code that uses plain `for..in` to iterate over arrays.
It would be better for you to create your own type of object constructor complete with doSomething function, rather than extending the built-in Array.
**What about `Object.defineProperty`?**
There now exists `Object.defineProperty` as a general way of extending object prototypes without the new properties being enumerable, though this still doesn't justify extending the *built-in* types, because even besides `for..in` there is still the potential for conflicts with other scripts. Consider someone using two Javascript frameworks that both try to extend the Array in a similar way and pick the same method name. Or, consider someone forking *your* code and then putting both the original and forked versions on the same page. Will the custom enhancements to the Array object still work?
This is the reality with Javascript, and why you should avoid modifying the prototypes of built-in types, even with `Object.defineProperty`. Define your own types with your own constructors. | adding custom functions into Array.prototype | [
"",
"javascript",
"arrays",
"internet-explorer",
""
] |
I have some code like:
```
good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
```
The goal is to split up the contents of `mylist` into two other lists, based on whether or not they meet a condition.
How can I do this more elegantly? Can I avoid doing two separate iterations over `mylist`? Can I improve performance by doing so? | > ```
> good = [x for x in mylist if x in goodvals]
> bad = [x for x in mylist if x not in goodvals]
> ```
>
> is there a more elegant way to do this?
That code is perfectly readable, and extremely clear!
```
# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]
IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
images = [f for f in files if f[2].lower() in IMAGE_TYPES]
anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
```
Again, this is *fine!*
There might be slight performance improvements using sets, but it's a trivial difference, and I find the list comprehension far easier to read, and you don't have to worry about the order being messed up, duplicates being removed as so on.
In fact, I may go another step "backward", and just use a simple for loop:
```
images, anims = [], []
for f in files:
if f.lower() in IMAGE_TYPES:
images.append(f)
else:
anims.append(f)
```
The a list-comprehension or using `set()` is fine until you need to add some other check or another bit of logic - say you want to remove all 0-byte jpeg's, you just add something like..
```
if f[1] == 0:
continue
``` | Iterate manually, using the condition to select a list to which each element will be appended:
```
good, bad = [], []
for x in mylist:
(bad, good)[x in goodvals].append(x)
``` | How can I partition (split up, divide) a list based on a condition? | [
"",
"python",
"list",
""
] |
I'm using a picturebox to display images in a form. If the image is 10X10 pixels and the picturebox size is 100X100 I would like to make the image larger for using the whole picturebox area. When using the zoom property for the picturebox the pixels of the image is smeared out. How to fill the area of the picturebox with a smaller Image and maintain the pixel quality of the image. | You might want to look into creating your own exploded bitmap and then set that as the image of your `PictureBox`. The most naive approach would be to create a new 100x100 `Bitmap`, and [`SetPixel`](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.setpixel.aspx) in 10x10 blocks. | Given lc's suggestion, you could see [this](http://answers.google.com/answers/threadview/id/773698.html) link for some libraries to use. | Enlarge image without smearing pixels | [
"",
"c#",
"image",
"picturebox",
""
] |
I'm building a XML document dynamically where I create a a text node with CreateTextNode(**text**) method.
Now in case the **text** contains XML it will be XML encoded.
For instance:
```
text = "some <b>bolded</b> text"
```
How do you insert the text without being XML encoded.
EDIT:
I'm building a XML document with XmlDocument and insert elements and nodes.
The final output should not contain CDATA sections or encoded parts.
For instace I want the final output to look like this, where the text comes from a setting:
```
<root><p>Some <b>bolded</b> text</p></root>
``` | If you want the **text** to be `"some <b>bolded</b> text"`, then encoding is the **right** thing - otherwise it isn't (just) a text node. You could CDATA it, but I do not think that is what you mean either.
Do you want the XML contents to be the above text (so that it gets a `<b>...</b>` **element** inside it)?
---
Here's code that adds the content via various methods:
```
string txt = "some <b>bolded</b> text";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<xml><foo/></xml>");
XmlElement foo = (XmlElement)doc.SelectSingleNode("//foo");
// text: <foo>some <b>bolded</b> text</foo>
foo.RemoveAll();
foo.InnerText = txt;
Console.WriteLine(foo.OuterXml);
// xml: <foo>some <b>bolded</b> text</foo>
foo.RemoveAll();
foo.InnerXml = txt;
Console.WriteLine(foo.OuterXml);
// CDATA: <foo><![CDATA[some <b>bolded</b> text]]></foo>
foo.RemoveAll();
foo.AppendChild(doc.CreateCDataSection(txt));
Console.WriteLine(foo.OuterXml);
``` | Insert it into a [CDATA](http://en.wikipedia.org/wiki/CDATA) section:
```
<![CDATA[some <b>bolded</b> text]]>
``` | Insert text node to XML document containing XML | [
"",
"c#",
"xml",
""
] |
Does anyone know if there are plans to implement JavaScript in MS Visual Studio, like they do all the other languages?
I am fairly new to coding in JavaScript, but I have come to realise how powerful a language it really is for creating RIA. The main problem is that when it comes to developing and debugging in the IDE, it’s nowhere near as slick as if I was writing in say C#.
Maybe this is just a limitation of visual studio and that there are much better environments in which to code JavaScript?
Above all the most important thing is debugging. Currently when I attach and step through the whole process is very clunky. | VS 2010 will have much better [support for Javascript](http://blogs.msdn.com/mikeormond/archive/2009/04/16/visual-studio-2010-enhancements-for-asp-net.aspx) and intellisense
> Further enhancements in VS2010 will
> see vast performance improvements,
> particularly with large script
> libraries and the ability to recognise
> dynamically generated objects and
> other techniques used by many
> Javascript frameworks that the
> Intellisense engine in VS2008
> struggles with. Significant efforts
> have been made to improve the
> Intellisense compatibility with 3rd
> party libraries as well.
There's also [Spket IDE](http://spket.com/) exclusively for Javascript and XML development. | JavaScript works fine in Visual Studio 2008. It supports jQuery with full intellisense, and if I remember correctly, the debugger also supports JavaScript, at least in Web applications (though I'm not sure about that). I tend to do the debugging work in a browser though, because, well, that's where the action happens anyway. | JavaScript in Microsoft Visual Studio | [
"",
"javascript",
"visual-studio",
"ide",
""
] |
I have a long-running script that seems to occasionally report the following NOTICE-level error:
> *pg\_send\_query(): Cannot set connection to blocking mode*
It seems to continue to send queries afterward, but it's unclear if it successfully sends the query that generates the error.
What is this a symptom of?
**Edit:** There are no entries in the postgres log at the time the error occurred, suggesting this is solely a connection error, not something going wrong on postgres' side (e.g. probably not the result of postgres crashing and restarting or something)
**Edit:** As far as I can tell, my INSERT statements are succeeding, one way or another, when this error is triggered.
**Edit:** Looks like this may have been fixed in June 2013: <https://bugs.php.net/bug.php?id=65015> | It is a symptom of `pg_send_query()` not being able to successfully switch the connection back to blocking mode. Looking at the source code in PHPs pgsql.c, you can find:
```
/* {{{ proto bool pg_send_query(resource connection, string query)
Send asynchronous query */
PHP_FUNCTION(pg_send_query)
{
<... snipped function setup stuff ...>
if (PQ_SETNONBLOCKING(pgsql, 1)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
RETURN_FALSE;
}
<... snipped main function execution stuff ...>
if (PQ_SETNONBLOCKING(pgsql, 0)) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
}
RETURN_TRUE;
}
```
So the error gets raised at the end of the function, after the main work is done. This fits with your observation that your INSERT statements get executed.
The whole purpose of the two `PQ_SETNONBLOCKING` calls is to put the connection in non blocking mode to allow asynchronous execution and putting it back to the default blocking behaviour afterwards. From the [documentation of PQsetnonblocking](http://www.postgresql.org/docs/8.3/static/libpq-async.html): (PQ\_SETNONBLOCKING is just an alias defined for that function):
> Sets the nonblocking status of the
> connection.
>
> ```
> int PQsetnonblocking(PGconn *conn, int arg);
> ```
>
> Sets the state of the connection to nonblocking if arg is 1,
> or blocking if arg is 0. Returns 0 if
> OK, -1 if error.
>
> In the nonblocking state, calls to
> PQsendQuery, PQputline, PQputnbytes,
> and PQendcopy will not block but
> instead return an error if they need
> to be called again.
>
> Note that PQexec does not honor
> nonblocking mode; if it is called, it
> will act in blocking fashion anyway.
Looking further at the source of PQsetnonblocking (in PostgeSQLs fe-exec.c), there are two possible reasons why the call could fail:
```
/* PQsetnonblocking:
* sets the PGconn's database connection non-blocking if the arg is TRUE
* or makes it non-blocking if the arg is FALSE, this will not protect
* you from PQexec(), you'll only be safe when using the non-blocking API.
* Needs to be called only on a connected database connection.
*/
int
PQsetnonblocking(PGconn *conn, int arg)
{
bool barg;
if (!conn || conn->status == CONNECTION_BAD)
return -1;
barg = (arg ? TRUE : FALSE);
/* early out if the socket is already in the state requested */
if (barg == conn->nonblocking)
return 0;
/*
* to guarantee constancy for flushing/query/result-polling behavior we
* need to flush the send queue at this point in order to guarantee proper
* behavior. this is ok because either they are making a transition _from_
* or _to_ blocking mode, either way we can block them.
*/
/* if we are going from blocking to non-blocking flush here */
if (pqFlush(conn))
return -1;
conn->nonblocking = barg;
return 0;
}
```
So either the connection got lost somehow, or pqFlush did not finish successfully, indicating leftover stuff in the connection output buffer.
The first case would be harmless, as your script would certainly notice the lost connection for later calls and react to that (or fail more noticeable).
This leaves the second case, which would mean you have a connection in the non default, non blocking state. I do not know if this could affect later calls that would reuse this connection. If you want to play it safe, you'd close the connection in this case and use a new/other one. | It sounds like you're trying to use the `pg_send_query()` function for sending asynchronous queries to PostgreSQL. The purpose of this function is to allow your PHP script to continue executing other code while waiting for PostgreSQL to execute your query and make a result ready.
The example given in the [docs](http://php.net/manual/en/function.pg-send-query.php) for `pg_send_query()` suggest that you shouldn't send a query if PostgreSQL is already chewing on another query:
```
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
```
Is there a reason you're using `pg_send_query()` instead of `pg_query()`? If you can allow your script to block waiting for query execution, I'm guessing (admittedly without having tried it) that you won't see these errors. | pg_send_query(): Cannot set connection to blocking mode? | [
"",
"php",
"postgresql",
""
] |
Has anyone been able to get Oracle Forms running JInitator to loan in Internet Explorer 8 yet? I have tried removing all add-ons, various version of Java, add the domain to the trusted sites using wildcards, and using compatibility mode to no avail. I am looking to get our Oracle guys to kick there Internet Explorer 6 habit. This is related to Oracle E-Business. | To solve this problem you need to replace the file C:\Program Files\Oracle\JInitiator x.x.x.xx\bin\hotspot\jvm.dll with the sun version of the file.
On my system the sun version is here C:\Program Files\Java\jre6\bin\client\jvm.dll | Replacing the jvm.dll did not work for me. The proper way to switch to Sun's Java VM which worked for me is by changing this
```
baseHTMLjinitiator=basejini.htm
```
to
this
```
baseHTMLjinitiator=basejpi.htm
```
in the formsweb.cfg file. IE8 on XP SP3, DEP enabled. | Oracle Forms/Applications in Internet Explorer 8 using JInitator | [
"",
"java",
"oracle",
"internet-explorer",
"web-applications",
"oracleforms",
""
] |
I am attempting to add a javascript confirm dialog to either my linkbutton onclick event or my form onsubmit event.
Neither of them work as I receive an 'object expected' error from the browser.
```
frm.Attributes.Add("onsubmit", "return Confirm('Really do this?')")
```
How do I add a confirm dialog to the 'onsubmit' or 'onclick' events without generating an 'object expected' error? | confirm method should be all lowercase letters
Ex
```
confirm('Really do this?')
``` | use `OnClientClick="return confirm('Message')"` | Adding Javascript Confirm Dialog to LinkButton/Form generates Object Expected error | [
"",
"asp.net",
"javascript",
"object-expected",
""
] |
How do you install the source for the java libraries in Eclipse? | This happens automatically if you set up a JDK rather than a JRE.
Normally, when you start eclipse, it sets up the JRE that was used to start eclipse. You'll usually want to override this with a JDK so you get the source. To do this:
1. First, make sure you have a JDK installed (and not just a JRE)
2. Start eclipse
3. Go to Window->Preferences->Java->Installed JREs
4. Press Add...
5. Choose "Standard VM" and press "Next..."
6. Press "Directory...", select the JDK installation directory and press "Ok"
7. Press "Finish"
8. Make sure you check the box next to the new JDK
9. Press "Ok" to finish up
This will set up the source properly for you. | You can do it in the project preferences, but I find quite faster just to ctr+click over a object or class defined in the standard library and then "attach source" in the page that will gently inform you that there are no sources attached.
You then can point to the "src.zip" in your JDK distribution. | How Do You Install the source for the java libraries in Eclipse? | [
"",
"java",
"eclipse",
""
] |
How do I programmatically determine the network connection link speed for an active network connection - like Task Manager shows you in the Networking tab? I'm not really after the bandwidth available, just a figure for the current connection, e.g. 54Mbps, 100Mbps etc. | In the end I found the [`Win32_PerfRawData_Tcpip_NetworkInterface`](http://msdn.microsoft.com/en-us/library/aa394340(VS.85).aspx) WMI class, as I need to support legacy platforms which, unfortunately, the `Win32_NetworkAdapter` doesn't do. `Win32_PerfRawData_Tcpip_NetworkInterface` has a `CurrentBandwidth` property which gives me what I need on all required platforms (I realise I said I didn't need "bandwidth" but its acceptable and appears to return the "nominal bandwidth" of the adapter anyway).
Thanks to all those who posted, pointing me in the right direction. | [`Win32_NetworkAdapter`](http://msdn.microsoft.com/en-us/library/aa394216(VS.85,loband).aspx) WMI class can help you (`Speed` property). It returns the value 54000000 for my WiFi adapter connected to a WiFi-g access point. | Determining the network connection link speed | [
"",
"c++",
"windows",
"winapi",
"networking",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.