Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a seemingly simple problem though i am unable to get my head around it.
Let's say i have the following string: 'abcabcabcabc' and i want to get the last occurrence of 'ab'. Is there a way i can do this *without* looping through all the other 'ab's from the beginning of the string?
I read about anchoring the end of the string and then parsing the string with the required regular expression. I am unsure how to do this in Java (is it supported?).
**Update:** I guess i have caused a lot of confusion with my (over) simplified example. Let me try another one. Say, i have a string as thus - '12/08/2008 some\_text 21/10/2008 some\_more\_text 15/12/2008 and\_finally\_some\_more'. Here, i want the **last date** and hence i need to use regular expressions. I hope this is a better example.
Thanks,
Anirudh | Firstly, thanks for all the answers.
Here is what i tried and this worked for me:
```
Pattern pattern = Pattern.compile("(ab)(?!.*ab)");
Matcher matcher = pattern.matcher("abcabcabcd");
if(matcher.find()) {
System.out.println(matcher.start() + ", " + matcher.end());
}
```
This displays the following:
```
6, 8
```
So, to generalize - `<reg_ex>(?!.*<reg_ex>)` should solve this problem where '?!' signifies that the string following it should not be present after the string that precedes '?!'.
**Update:** [This page](http://www.kleenecode.net/2008/10/10/regex-fu-not-followed-by/) provides a more information on 'not followed by' using regex. | This will give you the last date in group 1 of the match object.
```
.*(\d{2}/\d{2}/\d{4})
``` | Parsing text from the end (using regular expressions) | [
"",
"java",
"regex",
""
] |
I want to develop a program that can hide a folder. Not a hidden attribute, but a real hiding so that no applications can find it. I think for that I need to create a file system driver.
How can I do it in C#? | I think i have to create a file system filter driver for what i really want. Its not just changing attribute | You can't do it in C#.
You may find these videos interesting. Inside file system filters [Part1](http://channel9.msdn.com/shows/Going+Deep/Neal-Christiansen-Inside-File-System-Filter-part-I/) & [Part2](http://channel9.msdn.com/shows/Going+Deep/Neal-Christiansen-Inside-File-System-Filter-part-II/). | How can I hide a directory in C# with a file system driver? | [
"",
"c#",
".net",
"filesystems",
""
] |
In Python, I can compile a regular expression to be case-insensitive using `re.compile`:
```
>>> s = 'TeSt'
>>> casesensitive = re.compile('test')
>>> ignorecase = re.compile('test', re.IGNORECASE)
>>>
>>> print casesensitive.match(s)
None
>>> print ignorecase.match(s)
<_sre.SRE_Match object at 0x02F0B608>
```
Is there a way to do the same, but without using `re.compile`. I can't find anything like Perl's `i` suffix (e.g. `m/test/i`) in the documentation. | Pass `re.IGNORECASE` to the `flags` param of [`search`](https://docs.python.org/library/re.html#re.search), [`match`](https://docs.python.org/library/re.html#re.match), or [`sub`](https://docs.python.org/library/re.html#re.sub):
```
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
``` | You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):
```
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
``` | Case insensitive regular expression without re.compile? | [
"",
"python",
"regex",
"case-sensitive",
"case-insensitive",
""
] |
I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.
This script was a basis for entering numeric values only, however it needs to be adapted so it can take a decimal point followed by only up to two decimal places.
I've tried things such as `/[^\d].\d{0,2}`, but then the replacement call wouldn't work, and I've got no idea how to do it.
## Code
```
<script type="text/JavaScript">
function valid(f) {
if (!/^\d*$/.test(f.value)) {
f.value = f.value.replace(/[^\d]/g,"");
alert("Invalid number");
}
}
</script>
```
---
### Note
I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero. | The . character has special meaning in RegEx so needs escaping.
```
/^(?:\d*\.\d{1,2}|\d+)$/
```
This matches 123.45, 123.4, 123 and .2, .24 but not emtpy string, 123., 123.456 | `.` means in RegEx: any character, you have to put a backslash infront of it. `\.`
This would be better:
```
/^\d+(\.\d{0,2})?$/
```
Parts I included:
* You need at least 1 number in front of the dot. If you don't want this, replace `+` with `*` but then also empty strings would be matched.
* If you have decimal values you need the dot in front.
* There shouldn't be anything after the number, `$` stands for the end of the input.
and for the replacing part you should also include the dot
```
f.value.replace(/[^\d\.]/g, "")
```
**Edit:**
If it's for the live validation of inputs, why don't you just either intercept keyevents and test for their validity (by creating the string in memory) or just delete the last character in the field? | JavaScript Decimal Place Restriction With RegEx | [
"",
"javascript",
"regex",
""
] |
I've read a couple of blog post mentioning that for public APIs we should always return ICollection (or IEnumerable) instead of List. What is the real advantage of returning ICollection instead of a List?
Thanks!
Duplicate: [What is the difference between List (of T) and Collection(of T)?](https://stackoverflow.com/questions/398903/what-is-the-difference-between-list-of-t-and-collectionof-t) | An enumerator only returns one entity at a time as you iterate over it. This is because it uses a **yield return**. A collection, on the other hand, returns the entire list, requiring that the list be stored completely in memory.
The short answer is that enumerators are lighter and more efficient. | It gives you more freedom when choosing the Underlying data structure.
A List assumes that the implementation supports indexing, but ICollection makes no such assumption.
This means that if you discover that a Set might provide better performance since ordering is irrelevant, then you're free to change your approach without affecting clients.
It's basic encapsulation. | What is the real advantage of returning ICollection<T> instead of a List<T>? | [
"",
"c#",
".net",
"ienumerable",
"icollection",
""
] |
How would you generate an JPG image file containing data fields that are stored and updated within a database table? The image would then be regenerated every hour or so reflecting the latest values within the database table.
You would start with a basic background image, and then the generated image should contain data fields (e.g. average temperature, cpu load, time since last reboot etc.) overlayed on top of the background image. The data would be visualized with nice charts, icons and fonts.
Thanks!
EDIT: Good stuff. There are many good suggestions covering charting especially like JFreechart. I'm still a bit unsure on how best to work with overlaying images (i.e. icons) over a background image. Would the basic Java API be best for this case?
TIA! | Check out the [**Java Tutorial on 2D Graphics**](http://java.sun.com/docs/books/tutorial/2d/index.html). You could load your background image as a [`BufferedImage`](http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html) using [`ImageIO.read()`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#read(java.io.File)), and then draw text on it using [`Graphics.drawString()`](http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html#drawString(java.lang.String,%20int,%20int)). You could then save the image using [`ImageIO.write()`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#write(java.awt.image.RenderedImage,%20java.lang.String,%20java.io.File)).
---
The OP has added more sophisticated requirements (nice charts, icons and fonts). In this case, one of the many charting or reporting packages (e.g. [JFreeChart](http://www.jfree.org/jfreechart/), [JasperForge](http://jasperforge.org/)) would be more suitable. | you could use jfreechart
here is some nice tutorial
<http://www.oracle.com/technology/pub/articles/marx-jchart.html> | Generating an image with data fields using Java | [
"",
"java",
"image",
"image-generation",
""
] |
I have the following table containing the winning numbers of 6/49 lottery.
```
+-----+------------+----+----+----+----+----+----+-------+
| id | draw | n1 | n2 | n3 | n4 | n5 | n6 | bonus |
+-----+------------+----+----+----+----+----+----+-------+
| 1 | 1982-06-12 | 3 | 11 | 12 | 14 | 41 | 43 | 13 |
| 2 | 1982-06-19 | 8 | 33 | 36 | 37 | 39 | 41 | 9 |
| 3 | 1982-06-26 | 1 | 6 | 23 | 24 | 27 | 39 | 34 |
| 4 | 1982-07-03 | 3 | 9 | 10 | 13 | 20 | 43 | 34 |
| 5 | 1982-07-10 | 5 | 14 | 21 | 31 | 34 | 47 | 45 |
| 6 | 1982-07-17 | 8 | 20 | 21 | 25 | 31 | 41 | 33 |
| 7 | 1982-07-24 | 18 | 25 | 28 | 33 | 36 | 42 | 7 |
| 8 | 1982-07-31 | 7 | 16 | 17 | 31 | 40 | 48 | 26 |
| 9 | 1982-08-07 | 5 | 10 | 23 | 27 | 37 | 38 | 33 |
| 10 | 1982-08-14 | 4 | 15 | 30 | 37 | 46 | 48 | 3 |
+-----+------------+----+----+----+----+----+----+-------+
```
I would like to create a frequency chart to see the occurrence of numbers in n1, n2,...,n6 columns.
```
SELECT n1, COUNT(n1) as freq1 FROM lottery GROUP BY n1;
SELECT n2, COUNT(n2) as freq2 FROM lottery GROUP BY n2;
SELECT n3, COUNT(n3) as freq3 FROM lottery GROUP BY n3;
SELECT n4, COUNT(n4) as freq4 FROM lottery GROUP BY n4;
SELECT n5, COUNT(n5) as freq5 FROM lottery GROUP BY n5;
SELECT n6, COUNT(n6) as freq6 FROM lottery GROUP BY n6;
```
Basically I'm trying to combine the above queries into one query.
Thanks in advance. | Given your table layout, you can't combine the queries into a single one by any other means than to union your queries, or to union your base table into a transposed version:
```
SELECT n, COUNT(*) as freq FROM
(
SELECT n1 AS n FROM lottery
UNION ALL
SELECT n2 FROM lottery
UNION ALL
SELECT n3 FROM lottery
UNION ALL
SELECT n4 FROM lottery
UNION ALL
SELECT n5 FROM lottery
UNION ALL
SELECT n6 FROM lottery
) as transposed
GROUP BY n
ORDER BY COUNT(*) DESC
``` | I would do something very similar, but try to reduce the number of records returned by the sub query...
```
SELECT
n AS [n],
SUM([data].count_n) AS [count_n]
FROM
(
SELECT n1 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n1
UNION ALL
SELECT n2 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n2
UNION ALL
SELECT n3 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n3
UNION ALL
SELECT n4 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n4
UNION ALL
SELECT n5 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n5
UNION ALL
SELECT n6 AS [n], COUNT(*) AS [count_n] FROM lottery GROUP BY n6
)
as [data]
GROUP BY
[data].n
ORDER BY
SUM([data].count_n) DESC
``` | SQL joining a few count(*) group by selections | [
"",
"sql",
""
] |
Let's say I have the following model:
```
class Contest:
title = models.CharField( max_length = 200 )
description = models.TextField()
class Image:
title = models.CharField( max_length = 200 )
description = models.TextField()
contest = models.ForeignKey( Contest )
user = models.ForeignKey( User )
def score( self ):
return self.vote_set.all().aggregate( models.Sum( 'value' ) )[ 'value__sum' ]
class Vote:
value = models.SmallIntegerField()
user = models.ForeignKey( User )
image = models.ForeignKey( Image )
```
The users of a site can contribute their images to several contests. Then other users can vote them up or down.
Everything works fine, but now I want to display a page on which users can see all contributions to a certain contest. The images shall be ordered by their score.
Therefore I have tried the following:
```
Contest.objects.get( pk = id ).image_set.order_by( 'score' )
```
As I feared it doesn't work since `'score'` is no database field that could be used in queries. | Oh, of course I forget about new aggregation support in Django and its `annotate` functionality.
So query may look like this:
```
Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' )
``` | You can write your own sort in Python very simply.
```
def getScore( anObject ):
return anObject.score()
objects= list(Contest.objects.get( pk = id ).image_set)
objects.sort( key=getScore )
```
This works nicely because we sorted the list, which we're going to provide to the template. | A QuerySet by aggregate field value | [
"",
"python",
"django",
"database",
""
] |
In your experience what are some good Hibernate performance tweaks? I mean this in terms of Inserts/Updates and Querying. | Some Hibernate-specific performance tuning tips:
* Avoid join duplicates caused by parallel to-many assocation fetch-joins (hence avoid duplicate object instantiations)
* Use lazy loading with fetch="subselect" (prevents N+1 select problem)
* On huge read-only resultsets, don't fetch into mapped objects, but into flat DTOs (with Projections and AliasToBean-ResultTransformer)
* Apply HQL Bulk Update, Bulk Delete and Insert-By-Select
* Use FlushMode.Never where appropriate
Taken from <http://arnosoftwaredev.blogspot.com/2011/01/hibernate-performance-tips.html> | I'm not sure this is a tweak, but join fetch can be useful if you have a many-to-one that you know you're going to need. For example, if a Person can be a member of a single Department and you know you're going to need both in one particular place you can use something like from Person p left join fetch p.department and Hibernate will do a single query instead of one query for Person followed by n queries for Department.
When doing a lot of inserts/updates, call flush periodically instead of after each save or at the end - Hibernate will batch those statements and send them to the database together which will reduce network overhead.
Finally, be careful with the second level cache. If you know the majority of the objects you read by id will be in the cache, it can make things really fast, but if count on them being there but don't have it configured well, you'll end up doing a lot of single row database queries when you could have brought back a large result set with only one network/database trip. | Hibernate Performance Tweaks | [
"",
"sql",
"performance",
"hibernate",
"jpa",
""
] |
When I use the XML serializer to serialize a `DateTime`, it is written in the following format:
```
<Date>2007-11-14T12:01:00</Date>
```
When passing this through an XSLT stylesheet to output HTML, how can I format this? In most cases I just need the date, and when I need the time I of course don't want the "funny T" in there. | Here are a couple of 1.0 templates that you can use:-
```
<xsl:template name="formatDate">
<xsl:param name="dateTime" />
<xsl:variable name="date" select="substring-before($dateTime, 'T')" />
<xsl:variable name="year" select="substring-before($date, '-')" />
<xsl:variable name="month" select="substring-before(substring-after($date, '-'), '-')" />
<xsl:variable name="day" select="substring-after(substring-after($date, '-'), '-')" />
<xsl:value-of select="concat($day, ' ', $month, ' ', $year)" />
</xsl:template>
<xsl:template name="formatTime">
<xsl:param name="dateTime" />
<xsl:value-of select="substring-after($dateTime, 'T')" />
</xsl:template>
```
Call them with:-
```
<xsl:call-template name="formatDate">
<xsl:with-param name="dateTime" select="xpath" />
</xsl:call-template>
```
and
```
<xsl:call-template name="formatTime">
<xsl:with-param name="dateTime" select="xpath" />
</xsl:call-template>
```
where xpath is the path to an element or attribute that has the standard date time format. | Date formatting is not easy in XSLT 1.0. Probably the most elegant way is to write a short XSLT extension function in C# for date formatting. Here's an example:
```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:myExtension="urn:myExtension"
exclude-result-prefixes="msxsl myExtension">
<xsl:output method="xml" indent="yes"/>
<msxsl:script implements-prefix="myExtension" language="C#">
<![CDATA[
public string FormatDateTime(string xsdDateTime, string format)
{
DateTime date = DateTime.Parse(xsdDateTime);
return date.ToString(format);
}
]]>
</msxsl:script>
<xsl:template match="date">
<formattedDate>
<xsl:value-of select="myExtension:FormatDateTime(self::node(), 'd')"/>
</formattedDate>
</xsl:template>
</xsl:stylesheet>
```
With this input document
```
<?xml version="1.0" encoding="utf-8"?>
<date>2007-11-14T12:01:00</date>
```
you will get
```
<?xml version="1.0" encoding="utf-8"?>
<formattedDate>14.11.2007</formattedDate>
```
The function formatting the date takes a date value as string and a format as described in [DateTime.ToString Method](http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx). Using .NET's DateTime struct gives you parsing arbitrary XSD datetime values (including time zone specifiers), timezone calculation and localized output for free.
However, be aware that there is one [caveat (http://support.microsoft.com/kb/316775)](http://support.microsoft.com/kb/316775) with msxml script extensions: Each time you load the XSLT an assembly containing the script code is generated dynamically and loaded into memory. Due to the design of the .NET runtime, this assembly cannot be unloaded. That's why you have to make sure that your XSLT is only loaded once (and then cached for further re-use). This is especially important when running inside IIS. | Format a date in XML via XSLT | [
"",
"c#",
".net",
"xml",
"datetime",
"xslt",
""
] |
For the following block of code:
```
For I = 0 To listOfStrings.Count - 1
If myString.Contains(lstOfStrings.Item(I)) Then
Return True
End If
Next
Return False
```
The output is:
**Case 1:**
```
myString: C:\Files\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: True
```
**Case 2:**
```
myString: C:\Files3\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: False
```
The list (listOfStrings) may contain several items (minimum 20) and it has to be checked against a thousands of strings (like myString).
Is there a better (more efficient) way to write this code? | With LINQ, and using C# (I don't know VB much these days):
```
bool b = listOfStrings.Any(s=>myString.Contains(s));
```
or (shorter and more efficient, but arguably less clear):
```
bool b = listOfStrings.Any(myString.Contains);
```
If you were testing equality, it would be worth looking at `HashSet` etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.
---
update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use `Array.BinarySearch` to find each item - check by lookup to see if it is a full or partial match.
Update: in the recent .Net, [Contains has optional StringComparison parameter](https://stackoverflow.com/questions/444798/case-insensitive-containsstring/52791476#52791476) , that can be used for case-insensitive comparison, e.g. myString.Contains(s,StringComparison.CurrentCultureIgnoreCase); | when you construct yours strings it should be like this
```
bool inact = new string[] { "SUSPENDARE", "DIZOLVARE" }.Any(s=>stare.Contains(s));
``` | Check if a string contains an element from a list (of strings) | [
"",
"c#",
"vb.net",
"list",
"coding-style",
"performance",
""
] |
while learning some basic programming with python, i found web.py. i
got stuck with a stupid problem:
i wrote a simple console app with a main loop that proccesses items
from a queue in seperate threads. my goal is to use web.py to add
items to my queue and report status of the queue via web request. i
got this running as a module but can´t integrate it into my main app.
my problem is when i start the http server with app.run() it blocks my
main loop.
also tried to start it with thread.start\_new\_thread but it still
blocks.
is there an easy way to run web.py´s integrated http server in the
background within my app.
in the likely event that i am a victim of a fundamental
missunderstanding, any attempt to clarify my error in reasoning would
help ;.) ( please bear with me, i am a beginner :-) | I found a working solution. In a seperate module i create my webserver:
```
import web
import threading
class MyWebserver(threading.Thread):
def run (self):
urls = ('/', 'MyWebserver')
app = web.application(urls, globals())
app.run()
def POST ...
```
In the main programm i just call
```
MyWebserver().start()
```
and than go on with whatever i want while having the webserver working in the background. | Wouldn't is be simpler to re-write your main-loop code to be a function that you call over and over again, and then call that from the function that you pass to `runsimple`...
It's guaranteed not to fully satisfy your requirements, but if you're in a rush, it might be easiest. | Using web.py as non blocking http-server | [
"",
"python",
"multithreading",
"web-services",
"web.py",
""
] |
mmm, I have just a little confusion about multiple auto declarations in the upcoming C++0x standard.
```
auto a = 10, b = 3.f , * c = new Class();
```
somewhere I read it is not allowed.
The reason was(?) because it was not clear if the consecutive declarations should have the same type of the first one , (int in the example) , or not.
Possible translation 1:
```
int a = 10;
int b = 3.f;
int * c = new Class ();
```
causing an error
Possible translation 2:
```
int a = 10;
float b = 3.f;
Class * c = new Class ();
```
how it is resulted in the standard?
If I can say my POV, translation #2 was the most obiouvs, at least for me that I'm a regular C++ user . I mean, for me "every variable declared is of the same declared type", witch is auto.
Translation #1 would be really un-intuitive to me.
Good Bye
QbProg | It's probably not the latest, but my C++0x draft standard from June 2008 says you can do the following:
```
auto x = 5; // OK: x has type int
const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int
```
So unless something has changed from June this is (or will be) permitted in a limited form with a pretty intuitive interpretation.
The limitation is that if you do want to string multiple auto declarations like this (using the example above), it works because the inferred type of `v` and `u` have the same 'base type' (int in this case) to use an inexact term.
If you want the precise rule, The draft standard says this:
> If the list of declarators contains more than one declarator, the type of each declared variable is determined as described
> above. If the type deduced for the template parameter U is not the same in each deduction, the program is ill-formed.
where the "deduced template parameter U" is determined by:
> the deduced type of the parameter u in the call f(expr) of the following invented function template:
>
> ```
> `template <class U> void f(const U& u);`
> ```
Why they've come up with this rule instead of saying something like:
```
auto a = 10, b = 3.f , * c = new Class();
```
is equivalent to:
```
auto a = 10;
auto b = 3.f;
auto * c = new Class();
```
I don't know. But I don't write compilers. Probably something to do with once you've figured out the the `auto` keyword replaces, you can't change it in the same statement.
Take for example:
```
int x = 5;
CFoo * c = new CFoo();
auto a1 = x, b1 = c; // why should this be permitted if
int a2 = x, CFoo* b2 = c; // this is not?
```
In any case, I'm not a fan of putting multiple declarations on the same statement anyway. | The [draft standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf) section 7.1.6.4 implies that you can't mix types like in possible translation 2. So neither possible translation is valid. | How the C++0x standard defines C++ Auto multiple declarations? | [
"",
"c++",
"c++11",
""
] |
I am facing a weird issue in IIS 7.0:
I have the following virtual directory in IIS:
[](https://i.stack.imgur.com/EEhGd.jpg)
**and only Windows Authentication mode is enabled on the virtual directory in IIS**
Now if I try to get associated DirectoryEntry for TestV/Folder/file.aspx in this manner:
```
string vDir = @"/TestV/folder/file.aspx";
DirectoryEntry dir = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT" + vDir, @"adminusername", @"password");
dir.AuthenticationType = AuthenticationTypes.Secure;
try
{
Console.WriteLine(dir.Name);
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
Console.WriteLine("");
```
I get the exception:
"The system cannot find the path specified"
Now if I go back to IIS and then perform the following steps:
Right click on TestV/Folder *and enable Anonymous authentication mode and then disable it again*
Right click on TestV/Folder/file.aspx *and enable Anonymous authentication mode and then disable it again*
Essentially i just performed some manual access on the aspx file Testv/Folder/file.aspx.
After the above steps if i re run the program, the code is successfully able to access the directory entry and successfully prints the name (file.aspx)
What is the problem here?
One more information:
I see this behavior on IIS 6.0 also. So it appears like until and unless I do some manual operation in IIS for a folder/file in virtual directory, it does not create the corresponding metadata in the active directory? | I got the answer to the problem (with some help from one of my colleagues)
Here is the solution:
1. The program needs to add (pseudo?)entries to the IIS metadata before it access the file/folder under the virtual directory, before we access the entry:
```
try
{
// make pseudo entries:
DirectoryEntry folder = rootDir.Children.Add("Folder", "IISWebDirectory");
folder.CommitChanges();
file = folder.Children.Add("File.aspx", "IISWebFile");
file.CommitChanges();
}
```
Then voila it works
PS:
```
DirectoryEntry dir = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT" + vDir, @"adminusername", @"password");
dir.AuthenticationType = AuthenticationTypes.Secure;
dir.RefreshCache();
```
**Directory.Refresh does not help** | Does it help if you call RefreshCache() right after the third line?
```
DirectoryEntry dir = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT" + vDir, @"adminusername", @"password");
dir.AuthenticationType = AuthenticationTypes.Secure;
dir.RefreshCache();
``` | Weird behaviour in IIS 7.0 - System.DirectoryServices | [
"",
"c#",
"iis-7",
"active-directory",
""
] |
In Sql Server 2005 when I have multiple parameters do I have the guarantee that the evaluation order will **always** be from left to right?
Using an example:
> `select a from table where c=1 and d=2`
In this query if the "c=1" condition fails the "d=2" condition will never be evaluated?
PS- "c" is an integer indexed column, d is a large varchar and non indexable column that requires a full table scan
**update** I was trying to avoid performing two queries or conditional statements, I just need something like: if "c condition" fails there's a way to avoid performing the heavy "d condition", since it's not needed in my case. | There are no guarantees for evaluation order. The optimizer will try to find the most efficient way to execute the query, using available information.
In your case, since c is indexed and d isn't, the optimizer should look into the index to find all rows that match the predicate on c, then retrieve those rows from the table data to evaluate the predicate on d.
However, if it determines that the index on c isn't very selective (although not in your example, a gender column is rarely usefully indexed), it may decide to do the table scan anyway.
To determine execution order, you should get an explain plan for your query. However, realize that that plan may change depending on what the optimizer thinks is the best query right now. | SQL Server will generate an optimized plan for each statement it executes. You don't have to order your where clause to get that benefit. The only garuntee you have is that it will run statements in order so:
```
SELECT A FROM B WHERE C
SELECT D FROM E WHERE F
```
will run the first line before the second. | Select "where clause" evaluation order | [
"",
"sql",
"sql-server",
"sql-server-2005",
"performance",
"select",
""
] |
I'm trying to pass a `ViewData` object from a master page to a view user control using the `ViewDataDictionary`.
The problem is the `ViewDataDictionary` is not returning any values in the view user control whichever way I try it.
The sample code below is using an anonymous object just for demonstration although neither this method or passing a `ViewData` object works.
Following is the `RenderPartial` helper method I'm trying to use:
```
<% Html.RenderPartial("/Views/Project/Projects.ascx", ViewData.Eval("Projects"), new ViewDataDictionary(new { Test = "Mark" })); %>
```
and in my view user control i do the following:
```
<%= Html.Encode(ViewData["Test"]) %>
```
Why does this not return anything?
Thanks for your help.
EDIT:
I'm able to pass and access the strongly typed model without any problems. it's the `ViewDataDictionary` which I'm trying to use to pass say just a single value outside of the model... | Have you tried:
```
<% Html.RenderPartial("~/Views/Project/Projects.ascx", ViewData); %>
```
Also have you verified ViewData["Test"] is in the ViewData before you are passing it? Also note that when passing your ViewData to a Partial Control that it is important to keep the Model the same.
Nick | This is the neatest way I've seen to do this:
```
<% Html.RenderPartial("/Views/Project/Projects.ascx", Model, new ViewDataDictionary{{"key","value"}});%>
```
It may be a little hackish, but it let's you send the model through AND some extra data. | asp.net MVC RC1 RenderPartial ViewDataDictionary | [
"",
"c#",
".net",
"asp.net-mvc",
""
] |
What are the pros and cons of using `System.Security.Cryptography.RNGCryptoServiceProvider` vs `System.Random`. I know that `RNGCryptoServiceProvider` is 'more random', i.e. less predictable for hackers. Any other pros or cons?
---
**UPDATE:**
According to the responses, here are the pros and cons of using `RNGCryptoServiceProvider` so far:
### Pros
* `RNGCryptoServiceProvider` is a stronger cryptographically random number, meaning it would be better for determining encryption keys and the likes.
### Cons
* `Random` is faster because it is a simpler calculation; when used in simulations or long calculations where cryptographic randomness isn't important, this should be used. Note: see [Kevin's answer](https://stackoverflow.com/a/54847919/9536) for details about simulations - `Random` is not necessarily random enough, and you may want to use a different non-cryptographic PRNG. | A cryptographically strong RNG will be slower --- it takes more computation --- and will be spectrally white, but won't be as well suited to simulations or Monte Carlo methods, both because they *do* take more time, and because they may not be repeatable, which is nice for testing.
In general, you want to use a cryptographic PRNG when you want a unique number like a UUID, or as a key for encryption, and a deterministic PRNG for speed and in simulation. | `System.Random` is not thread safe. | Pros and cons of RNGCryptoServiceProvider | [
"",
"c#",
".net",
"random",
""
] |
I have a table like this (Oracle, 10)
```
Account Bookdate Amount
1 20080101 100
1 20080102 101
2 20080102 200
1 20080103 -200
...
```
What I need is new table grouped by Account order by Account asc and Bookdate asc with a running total field, like this:
```
Account Bookdate Amount Running_total
1 20080101 100 100
1 20080102 101 201
1 20080103 -200 1
2 20080102 200 200
...
```
Is there a simple way to do it?
Thanks in advance. | Do you really need the extra table?
You can get that data you need with a simple query, which you can obviously create as a view if you want it to appear like a table.
This will get you the data you are looking for:
```
select
account, bookdate, amount,
sum(amount) over (partition by account order by bookdate) running_total
from t
/
```
This will create a view to show you the data as if it were a table:
```
create or replace view t2
as
select
account, bookdate, amount,
sum(amount) over (partition by account order by bookdate) running_total
from t
/
```
If you really need the table, do you mean that you need it constantly updated? or just a one off? Obviously if it's a one off you can just "create table as select" using the above query.
Test data I used is:
```
create table t(account number, bookdate date, amount number);
insert into t(account, bookdate, amount) values (1, to_date('20080101', 'yyyymmdd'), 100);
insert into t(account, bookdate, amount) values (1, to_date('20080102', 'yyyymmdd'), 101);
insert into t(account, bookdate, amount) values (1, to_date('20080103', 'yyyymmdd'), -200);
insert into t(account, bookdate, amount) values (2, to_date('20080102', 'yyyymmdd'), 200);
commit;
```
edit:
forgot to add; you specified that you wanted the table to be ordered - this doesn't really make sense, and makes me think that you really mean that you wanted the query/view - ordering is a result of the query you execute, not something that's inherant in the table (ignoring Index Organised Tables and the like). | Use analytics, just like in your last question:
```
create table accounts
( account number(10)
, bookdate date
, amount number(10)
);
delete accounts;
insert into accounts values (1,to_date('20080101','yyyymmdd'),100);
insert into accounts values (1,to_date('20080102','yyyymmdd'),101);
insert into accounts values (2,to_date('20080102','yyyymmdd'),200);
insert into accounts values (1,to_date('20080103','yyyymmdd'),-200);
commit;
select account
, bookdate
, amount
, sum(amount) over (partition by account order by bookdate asc) running_total
from accounts
order by account,bookdate asc
/
```
output:
```
ACCOUNT BOOKDATE AMOUNT RUNNING_TOTAL
---------- -------- ---------- -------------
1 01-01-08 100 100
1 02-01-08 101 201
1 03-01-08 -200 1
2 02-01-08 200 200
``` | Running total by grouped records in table | [
"",
"sql",
"oracle",
"grouping",
"sum",
"cumulative-sum",
""
] |
Lets say you have interface definition.
That interface can be *Operation*.
Then you have two applications running in different JVMs and communicating somehow remotely by exchanging *Operation* instances.
Lets call them application *A* and application *B*.
If application *A* implements *Operation* with the class that is not available in the classpath of the application *B*, will application *B* still be able to handle that implementation of interface? Even when *B* is in different JVM? | It depends on what you mean by "communicating somehow remotely". If application A *actually* just hands application B some sort of token which is built into a proxy such that calls to the Operation interface are proxied back to application A, then it may be okay. If the idea is for application B to create a local instance of the implementation class, then that's not going to work because it won't know what the object looks like. | It depends on the magic that happens in your "somehow communicate remotely" part.
If this communication is done via RMI or a similar technology, then this will be fine. Application B will create a remote proxy to the `Operation` object in JVM A, and calling methods on this proxy generate HTTP requests to JVM A, which are resolved against the actual object living in that JVM (which has access to the implementing class).
If this communication is done by serialising objects and sending them over the wire, then it will not work. When the object from application A arrives in JVM B, the deserialisation will fail (with a `ClassNotFoundException` or similar).
There could well be other remoting technologies, in which case things are implementation dependent. I know that Classloaders can load classes from byte arrays, and thus it's conceptually very possible to have such classloaders that would be able to load classes from remote sources. The networking library could in theory serialise the actual class across the wire this way, I believe, so while JVM B would not natively know about the implementing class, its classloader would be provided with the class' bytecode as required. | Interface implementation through different JVMs | [
"",
"java",
"jvm",
""
] |
I have a class 'Data' that uses a getter to access some array. If the array is null, then I want Data to access the file, fill up the array, and then return the specific value.
Now here's my question:
When creating getters and setters should you also use those same accessor properties as your way of accessing that array (in this case)? Or should you just access the array directly?
The problem I am having using the accessors from within the class is that I get infinite loops as the calling class looks for some info in Data.array, the getter finds the array null so goes to get it from the file, and that function ends up calling the getter again from within Data, array is once again null, and we're stuck in an infinite loop.
EDIT:
So is there no official stance on this? I see the wisdom in not using Accessors with file access in them, but some of you are saying to always use accessors from within a class, and others are saying to never use accessors from with the class............................................ | I agree with krosenvold, and want to generalize his advice a bit:
Do not use Property getters and setters for expensive operations, like reading a file or accessing the network. Use explicit function calls for the expensive operations.
Generally, users of the class will not expect that a simple property retrieval or assignment may take a lot of time.
[This is also recommended in Microsoft's Framework Design Guidelines.](http://msdn.microsoft.com/en-us/library/ms229054.aspx);
> **Do use a method, rather than a
> property, in the following situations**.
>
> The operation is orders of magnitude
> slower than a field set would be. If
> you are even considering providing an
> asynchronous version of an operation
> to avoid blocking the thread, it is
> very likely that the operation is too
> expensive to be a property. In
> particular, operations that access the
> network or the file system (other than
> once for initialization) should most
> likely be methods, not properties. | I think its a good idea to always use the accessors. Then if you need any special logic when getting or setting the property, you know that everything is performing that logic.
Can you post the getter and setter for one of these properties? Maybe we can help debug it. | Should you use accessor properties from within the class, or just from outside of the class? | [
"",
"c#",
".net",
""
] |
I want to insert a `pair< string, vector<float> >` into a map, first it works, but after several loops, it cannot insert any more and throw me a segmentation fault. Can anybody give a possible reason?
Btw: I first read a file and generate the map (about 200,000 elements) and I read another file and update the old map. the error occurs while the updating step.
Can anybody help me with the info I gave above? Thanks a lot
The code is pretty long.....I just erase the previous key and then insert a new one, it seems not complicated.....but drives me crazy....could you guess what happened here?
Thanks A lot for all your answers! And I found it is really a good place for solving problems. Thanks again, I'll try to simplify my codes and add it here today or tomorrow.
Update: I used the code from MSN and it works, thanks a lot that you solved my problem without seeing my code......also many thanks to other kind-hearted people here! However, i can only choose one as the answer. | The type in question is `pair<string, vector<float> >`. You will be copying that pair on every insert. If either the string or the vector are big then you could be running out of memory.
Edit: to fix running out of memory, you can change how you insert key-value pairs to:
```
pair<map::iterator, bool> insert_result= map.insert(make_pair(name, vector<float>());
if (insert.second) { insert_result.first->second.swap(vector_read_in); }
```
That will ensure that you do not copy memory, only move it. | Are you inserting using the iterator you called erase() on? Or using that iterator in any way? After erase(p) is called, p is invalidated. | Why did I get a Segmentation Fault with a map insert | [
"",
"c++",
""
] |
So I have a lot of projects coming that could use a little dhtml pizzaz and I don't know which frame work to use for which project and any help would be appreciated. | Really, you'll be fine with any of the major ones because they all can accomplish basically the same things and most have a lot of plugins and scripts that overlap. That said, I'd recommend either [jQuery](http://jquery.com/) or [MooTools](http://mootools.net).
**jQuery** - Large community. Very fast with latest update. Very easy for beginners. Lots of plugins.
**MooTools** - A little harder for beginners, but I really like its class-like structure and modularity. You can choose which parts of the framework you need and disregard the rest. The community isn't as good as jQuery's. Lots of plugins.
You'd also be fine with [Prototype](http://www.prototypejs.org/)/[Scriptaculous](http://script.aculo.us/), [YUI](http://developer.yahoo.com/yui/), [Dojo](http://dojotoolkit.org/), and a few others, though I'm not as familiar with their pros and cons.
An important thing to keep in mind, though, is not to use more than one library at a time. You can't use Mootools and Prototype together, but you shouldn't use the others together either because you're just unnecessarily adding to the page size. If you find a script you really like in one library, chances are that it exists in another.
You'll also get the best compression by gzipping your files when you serve them to the browser. | Also: [Comparison of Javascript libraries](https://stackoverflow.com/questions/35050/comparison-of-javascript-libraries), which liks to:
<http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks> | Could someone list the common javascript frameworks/libraries and the pros/cons of each? | [
"",
"ajax",
"dhtml",
"javascript",
""
] |
Wonder what the difference between:
```
static PROCESSWALK pProcess32First=(PROCESSWALK)GetProcAddress(hKernel,"Process32First");
...
pProcess32First(...);
```
what is hKernel? Look in [here](http://msdn.microsoft.com/en-us/library/windows/desktop/ms683212%28v=vs.85%29.aspx). You can replace with `GetModuleHandle()`
and
```
#include <Tlhelp32.h>
...
Process32First(...);
```
What are the differences, I wonder which I should use. Is there any difference in terms of best practices then? | NOTE: my answer assumes that the function is available either way, there are other things to consider if you are after non-exported functions.
If you use LoadLibrary and GetProcAddress, then you have the option running with reduced functionality if the required library isn't there. if you use the include and link directly the lib, and dll isn't there (or doesn't have the export due to wrong version) your app will simply fail to load.
It really only makes a difference if you want to use a function that isn't in all versions of a given dll. | In addition to what Evan said (which is correct), another important difference (IMHO) is that if you're dynamically loading functions, you need to have a typedef to cast the void\* to in order to call the function once it's loaded. Unless the header files which defines the function prototype for static linkage has a mechanism for also defining the typedef for the function pointer from the same template function definition code, you're going to end up with a duplicate function definition, probably in your code. If the external header definitions are ever updated (for example, with new definitions for 64bit data types), you risk runtime errors in your application unless you update the other function prototypes (these will not be caught at compile time, because of the c-style cast to the function typedef).
It's a subtle issue, but an important one to consider. I would use implicit ("static") linking if you can because of that issue, and if you're using dynamic loading, be aware of the issue, and structure your code to avoid problems in the future as best you can. | Should I use GetProcAddress or just include various win32 libraries? | [
"",
"c++",
"c",
"winapi",
""
] |
How to convert a Dictionary to a SortedDictionary?
In addition to general conversion (preserving types of key and values) I'm interested in swapping the keys and values as part of the conversion: have a `Dictionary<string, double>` and I want to convert it to a `SortedDictionary<double, string>`.
How do I do this using LINQ extension methods in C# 3.0? | Why use LINQ? There is a constructor for this:
```
new SortedDictionary<int, string>(existing);
```
You could *add* a `ToSortedDictionary` - but I wouldn't bother...
---
Note: this is an answer to the title of the question (convert a `Dictionary` to a `SortedDictionary` for the same types, if you need additional step that OP is looking for - swap key and values in the process - as shown in the updated problem, see [this answer](https://stackoverflow.com/questions/451717/how-do-i-convert-from-a-dictionary-to-a-sorteddictionary-using-linq-in-c#451900). | No LINQ is needed. SortedDictionary has a constructor to do the conversion.
```
public SortedDictionary<TKey,TValue> Convert<TKey,TValue>(Dictionary<TKey,TValue> map) {
return new SortedDictionary<TKey,TValue>(map);
}
``` | How do I convert from a Dictionary to a SortedDictionary using LINQ in C#? | [
"",
"c#",
"linq",
"dictionary",
""
] |
SQL Server 2005 has great `sys.XXX` views on the system catalog which I use frequently.
What stumbles me is this: why is there a `sys.procedures` view to see info about your stored procedures, but there is no `sys.functions` view to see the same for your stored functions?
Doesn't anybody use stored functions? I find them very handy for e.g. computed columns and such!
Is there a specific reason `sys.functions` is missing, or is it just something that wasn't considered important enough to put into the `sys` catalog views? Is it available in SQL Server 2008? | I find UDFs are very handy and I use them all the time.
I'm not sure what Microsoft's rationale is for not including a sys.functions equivalent in SQL Server 2005 (or SQL Server 2008, as far as I can tell), but it's easy enough to roll your own:
```
CREATE VIEW my_sys_functions_equivalent
AS
SELECT *
FROM sys.objects
WHERE type IN ('FN', 'IF', 'TF') -- scalar, inline table-valued, table-valued
``` | Another way to list functions is to make use of INFORMATION\_SCHEMA views.
```
SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'FUNCTION'
```
According to the Microsoft web site "Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables". In other words, the underlying System tables may change as SQL gets upgraded, but the views should still remain the same. | SQL Server - where is "sys.functions"? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"stored-functions",
""
] |
In .NET remoting what is the difference between RemotingConfiguration.RegisterWellKnownServiceType and RemotingServices.Marshal?
What I want to do is create an object in a Windows Service, then put it in as a remoting object and have the Windows Service and the Client both act on the remoting object.
I thought the below code would accomplish this.
```
FooRemoting foo = new FooRemoting();
RemotingConfiguration.RegisterWellKnownServiceType(typeof(FooRemoting), serverName, WellKnownObjectMode.Singleton);
RemotingServices.Marshal(foo);
``` | This is what I found.
```
RemotingConfiguration.RegisterWellKnownServiceType(typeof(FooRemoting),
serverName, WellKnownObjectMode.Singleton);
```
RegisterWellKnownServiceType will create the object and make it a Singleton to any client that consumes it, but a reference by the server is not created. The object is not created until a client ask for it, and the same object is used for any other clients.
```
RemotingServices.Marshal(foo);
```
Marshal will register an object that has been created by the server, in this case a windows service. Then server will then have reference to the object and the clients will consume the same object.
My issue was using the Marshal to register the remoting object. Over time the remoting object will disappear for clients to consume, i.e. no longer on the remoting object. The service would still keep its reference.
Then I tried the RegisterWellKnownServiceType and the clients keep getting the correct reference, however I could not get the service to have a reference to the same object.
The solution is overriding the remoting object in this case FooRemoting. If I overrode the InitializeLifetimeService and returned null, the client would never lose connection, and the service will,
keep the connection.
```
public override object InitializeLifetimeService()
{
//return base.InitializeLifetimeService();
return null;
}
```
In order to keep the object created by the service and have the client to use the same object you must use
```
RemotingServices.Marshal(foo);
```
and override InitializeLifetimeService to return null. | It is possible to expose MarshalByRefObjects which have parameterful constructors over remoting, and it's possible for users of the class to only deal with its interface.
I have created a small proof of concept project. It has 3 projects: Server, Client, and Core. Server and Client both reference Core but do not reference each other.
In core, we define a service interface:
```
namespace Core
{
public interface ICountingService
{
int Increment();
}
}
```
The server defines the concrete implementation, *which the client doesn't have a reference to*:
```
namespace Server
{
public class CountingService : MarshalByRefObject, ICountingService
{
private static int _value = 0;
public CountingService(int startValue)
{
_value = startValue;
}
public int Increment()
{ // not threadsafe!
_value++;
return _value;
}
}
}
```
The important bits to note are that it has a constructor with a parameter, it is a MarshalByRefObject, and it implements the interface in the core project.
The server project is a console app which sets up a remoting channel (arbitrarily over HTTP for this example), creates the service, and registers it with remoting:
```
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
namespace Server
{
class Program
{
static void Main(string[] args)
{
HttpServerChannel serverChannel = new HttpServerChannel(8234);
ChannelServices.RegisterChannel(serverChannel, false);
// Following line won't work at runtime as there is no parameterless constructor
//RemotingConfiguration.RegisterWellKnownServiceType(typeof(CountingService),
// "CountingService.rem", WellKnownObjectMode.Singleton);
CountingService countingService = new CountingService(5);
RemotingServices.Marshal(countingService, "CountingService.rem");
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}
```
The above code has registered the URL <http://localhost:8234/CountingService.rem> which holds the instantiated service, which will start counting from 5.
The client, also a console app, can then get a reference, *using the interface class:*
```
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using Core;
namespace Client
{
class Program
{
static void Main(string[] args)
{
HttpClientChannel serverChannel = new HttpClientChannel();
ChannelServices.RegisterChannel(serverChannel, false);
for (int i = 0; i < 5; i++)
{
ICountingService countingService =
(ICountingService)Activator.GetObject(typeof(ICountingService),
"http://localhost:8234/CountingService.rem");
int newValue = countingService.Increment();
Console.WriteLine("Value is " + newValue);
}
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
}
}
```
When the server and client are run, it prints values from 6 to 10.
Summary: client knows only about the interface; implementation constructor can have parameters; instantiation can be controlled by your own code rather than by .NET. Very useful when dealing with constructor-based dependency injection with remoting objects. | In .NET remoting what is the difference between RemotingConfiguration.RegisterWellKnownServiceType and RemotingServices.Marshal? | [
"",
"c#",
".net",
"remoting",
""
] |
I have the following code, for which I get the error:
**Warning**: mysqli\_stmt::bind\_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement in file.
If this is only a warning, shouldn't the code still work? I want to do a select \* and display all the data except one field, which I want to bind and handle separately. Is there any way around, or a better method? My solution at the moment(untried) is to bind the correct amount of variables to the results with getRecords, and then bind separately as a different name with getHtml.
What are the advanatges of binding, and is it necessary.
```
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$id = $_GET["id"];
$con = mysqli_connect("localhost", "user", "password", "db");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$con->set_charset("utf8");
echo "test outside loop";
if($cmd=="GetSaleData") {
echo "test inside loop";
if ($getRecords = $con->prepare("SELECT SELECT Product_NO, Product_NAME, SUBTITLE, CURRENT_BID, START_PRICE, BID_COUNT, QUANT_TOTAL, QUANT_SOLD, ACCESSSTARTS, ACCESSENDS, ACCESSORIGIN_END, USERNAME, BEST_BIDDER_ID, FINISHED, WATCH, BUYITNOW_PRICE, PIC_URL, PRIVATE_AUCTION, AUCTION_TYPE, ACCESSINSERT_DATE, ACCESSUPDATE_DATE, CAT_DESC, CAT_PATH, COUNTRYCODE, LOCATION, CONDITIONS, REVISED, PAYPAL_ACCEPT, PRE_TERMINATED, SHIPPING_TO, FEE_INSERTION, FEE_FINAL, FEE_LISTING, PIC_XXL, PIC_DIASHOW, PIC_COUNT, ITEM_SITE_ID FROM Sales WHERE Product_NO = ?")) FROM SaleS WHERE PRODUCT_NO = ?")) {
$getHtml = $con->prepare("SELECT PRODUCT_DESC FROM SaleS WHERE PRODUCT_NO = ?");
$getHtml->bind_param("i", $id);
$getHtml->execute();
$getHtml->bind_result($PRODUCT_DESC);
$getRecords->bind_param("i", $id);
$getRecords->execute();
$getRecords->bind_result($PRODUCT_NO, $PRODUCT_NAME, $SUBTITLE, $CURRENT_BID, $START_PRICE, $BID_COUNT, $QUANT_TOTAL, $QUANT_SOLD, $ACCESSSTARTS, $ACCESSENDS, $ACCESSORIGIN_END, $USERNAME, $BEST_BIDDER_ID, $FINISHED, $WATCH, $BUYITNOW_PRICE, $PIC_URL, $PRIVATE_Sale, $Sale_TYPE, $ACCESSINSERT_DATE, $ACCESSUPDATE_DATE, $CAT_DESC, $CAT_PATH, $COUNTRYCODE, $LOCATION, $CONDITIONS, $REVISED, $PAYPAL_ACCEPT, $PRE_TERMINATED, $SHIPPING_TO, $FEE_INSERTION,
$FEE_FINAL, $FEE_LISTING, $PIC_XXL, $PIC_DIASHOW, $PIC_COUNT, $ITEM_SITE_ID);
while ($getRecords->fetch()) {
// operations snipped for question
echo "<h1>".$PRODUCT_NAME."</h1>
<div id='leftlayer' class='leftlayer'>
<p><strong>Username: </strong>".$USERNAME."
<p><strong>Shipping to: </strong> ". $country ."
<img src='./images/".$id.".jpg"' width='".$imageSize["width"]."' height='".$imageSize["height"]."'>
</div>
<div id='rightlayer'>
</div>";
//
}
}
}
}
```
I would also like to know what is wrong with my img src statement..., I feel I am mising something elementary such as a slash or quote.
edit: The code now displays an error after replace \* with column names, however the while loop is never entered, and hence no actions are performed. | You may need to explicity state the column names in your SELECT rather than use \*, [as per the examples for MySQLi bind\_result()](http://www.php.net/manual/en/mysqli-stmt.bind-result.php).
In relation to the img line, you have an extra " after .jpg
```
<img src='./images/".$id.".jpg"' width=
```
should be
```
<img src='./images/".$id.".jpg width=
```
Also, you don't actually need to break out of the string and concatenate the variables because using " will cause the string to be parsed for variables anyway. | I'm guessing the problem is here:
```
$getRecords->bind_result($PRODUCT_NO, $PRODUCT_NAME, $SUBTITLE, $CURRENT_BID, $START_PRICE, $BID_COUNT, $QUANT_TOTAL, $QUANT_SOLD, $ACCESSSTARTS, $ACCESSENDS, $ACCESSORIGIN_END, $USERNAME, $BEST_BIDDER_ID, $FINISHED, $WATCH, $BUYITNOW_PRICE, $PIC_URL, $PRIVATE_Sale, $Sale_TYPE, $ACCESSINSERT_DATE, $ACCESSUPDATE_DATE, $CAT_DESC, $CAT_PATH, $COUNTRYCODE, $LOCATION, $CONDITIONS, $REVISED, $PAYPAL_ACCEPT, $PRE_TERMINATED, $SHIPPING_TO, $FEE_INSERTION,
$FEE_FINAL, $FEE_LISTING, $PIC_XXL, $PIC_DIASHOW, $PIC_COUNT, $ITEM_SITE_ID);
```
You are probably missing a column. The code will work if you have less columns than the retrieved in the result set.
As for the img tag, if you are on xhmtl you will have to close it. | mysqli binding fields in a prepared statement | [
"",
"php",
"mysql",
"ajax",
"mysqli",
""
] |
Earlier I asked why this is considered bad:
```
class Example
{
public:
Example(void);
~Example(void);
void f() {}
}
int main(void)
{
Example ex(); // <<<<<< what is it called to call it like this?
return(0);
}
```
Now, I understand that it's creating a function prototype instead that returns a type Example. I still don't get why it would work in g++ and MS VC++ though.
My next question is using the above, would this call be valid?
```
int main(void)
{
Example *e = new Example();
return(0);
}
```
? What is the difference between that and simply calling Example e()??? Like I know it's a function prototype, but it appears maybe some compilers forgive that and allow it to call the default constructor? I tried this too:
```
class Example
{
private:
Example();
public:
~Example();
};
int main(void)
{
Example e1(); // this works
Example *e1 = new Example(); // this doesn't
return(0);
}
```
So I'm a bit confused :( Sorry if this been asked a million times. | this [question](https://stackoverflow.com/questions/420099/is-this-type-variableoftype-function-or-object#420225) will be helpful to understand this behavior | It's easy, Daniel:
```
Example *e = new Example();
```
That doesn't look like a function called "Example", does it? A function has a return value, a name and parameters. How would the above fit that?
> Example e1(); // this works
Yeah, because you don't create any instance of `Example` anywhere. You just tell the code that there is a function defined in the surrounding namespace somewhere, and you possibly want to call that function. Yes, it's true that in order to return a object of Example, an instance would be made. But that doesn't mean an instance is made at that point. Rather, an instance is made in the function, when you call it. | C++ Classes default constructor | [
"",
"c++",
"constructor",
"class",
"default",
""
] |
I'm trying to find a simple MySQL statement for the following two problems:
I have 4 tables: Employees, Customers, Orders, Products (Each entry in Orders contains a date, a reference one product, a quantity and a reference to a customer, and a reference to an Employee).
Now I'm trying to get all customers where the volume of sale (quantity \* product.price) is bigger in 1996 than in 1995.
And: I want to list all Employees whose volume of sale is below the average volume of sale.
Any help would really be appreciated. I've managed to get the information using a php script but I think this can be done with some clever SQL Statements.
Can anybody help me?
---
Employee Table: ID# Name
Products Table: ID# NAME# PRICE
Orders Table: ODERID# CUSTOMERID # DATE # EMPLOYEE# PRODUCTID# QUANTITY | For the first part (assuming quite a bit about the schema):
```
SELECT Customers.ID
FROM Customers
LEFT JOIN orders AS o1 ON o1.CustomerID=Customers.ID AND YEAR(o1.DATE) = 1995
LEFT JOIN products AS p1 ON p1.id = o1.productID
LEFT JOIN orders AS o2 ON o2.CustomerID=Customers.ID AND YEAR(o2.DATE) = 1996
LEFT JOIN products AS p2 ON p2.id = o2.productID
HAVING SUM(o1.quantity* p1.price) < SUM(o2.quantity*p2.price)
``` | I don't know the database type you're using, so I'll use sqlserver. The 'Year' function is available on most databases, so you should be able to rewrite the query for your db in question.
I think this is the query which returns all customerid's + ordertotal for the customers which have a higher total in 1996 than in 1995, but I haven't tested it. Crucial is the HAVING clause, where you can specify a WHERE kind of clause based on the grouped result.
```
SELECT o.CustomerId, SUM(o.Quantity * p.Price) AS Total
FROM Orders o INNER JOIN Products p
ON o.ProductId = p.ProductId
WHERE YEAR(o.Date) == 1996
GROUP BY o.CustomerId
HAVING SUM(o.Quantity * p.Price) >
(
SELECT SUM(o.Quantity * p2.Price) AS Total
FROM Orders o2 INNER JOIN Products p2
ON o2.ProductId = p.ProductId
WHERE YEAR(o.Date) == 1995
AND o2.CustomerId = o.CustomerId
GROUP BY o.CustomerId
)
``` | SQL selection criteria on grouped aggregate | [
"",
"sql",
"mysql",
""
] |
I know I can "SELECT 5 AS foo" and get the resultset:
> **foo**
>
> 5
>
> (1 row)
...is there any way to "SELECT 5,6,7 AS foo" and get the resultset:
> **foo**
>
> 5
>
> 6
>
> 7
>
> (3 rows)
...I'm well aware that this is not typical DB usage, and any conceivable usage of this is probably better off going w/ a more ordinary technique. More of a technical question.
*Note: I know I could use a big gross list of UNIONs -- I'm trying to find something else.* | this is easy with a number table, here is an example
```
select number as foo
from master..spt_values
where type = 'p'
and number between 5 and 7
```
or if you want to use in
```
select number as foo
from master..spt_values
where type = 'p'
and number in(5,6,7)
``` | ```
select foo
from (select 1 as n1, 2 as n2, 3 as n3) bar
unpivot (foo for x in (n1, n2, n3)) baz;
``` | Is it possible to SELECT multiple constants into multiple resultset rows in SQL? | [
"",
"sql",
"sql-server",
""
] |
I'd like to convert an external XML document without any XSD schema associated with it into a fluent .NET object.
I have a simple XML file like:
```
<application>
<parameters>
<param></param>
<param></param>
</parameters>
<generation />
<entities>
<entity ID="1">
<PropTest>Test</PropTest>
</entity>
<entity ID="2">
<PropTest>Another Test</PropTest>
</entity>
</entities>
</application>
```
I'd like to navigate the document like:
```
var xConfig = new XmlConfig("file.xml");
// testValue should be assigned "Test"
string testValue = xConfig.Generation.Entities.Entity(1).PropTest;
```
What is the **best way to achieve this in .NET 3.5?** | Arguably, the best way to do this these days is with Linq to XML. It is a whole lot easier than messing with XSDs and convoluted class definitions.
```
XDocument doc = XDocument.Load("file.xml");
var val = doc
.Descendants("entity")
.Where(p => p.Attribute("ID").Value == "1")
.Descendants("PropTest")
.FirstOrDefault();
if (val != null)
Console.WriteLine(val.Value);
```
The sample file.xml that I used was:
```
<?xml version="1.0" encoding="utf-8" ?>
<application>
<parameters>
<param></param>
<param></param>
</parameters>
<generation>
<entities>
<entity ID="1">
<PropTest>Test</PropTest>
</entity>
<entity ID="2">Another Test</entity>
</entities>
</generation>
</application>
``` | I just noticed that [Lusid](https://stackoverflow.com/questions/461646/converting-an-xml-document-to-fluent-c/461786#461786) also wrote about Linq to SQL while I was writing my answer, but he used XDocument.
Here is my version (`file.xml` is the XML given in the question):
```
string testValue =
(string) XElement.Load("file.xml")
.Element("entities")
.Elements("entity")
.FirstOrDefault(entity => entity.Attribute("ID")
.Value == "1") ?? string.Empty;
``` | Converting an XML document to fluent C# | [
"",
"c#",
"xml",
".net-3.5",
"xsd",
"fluent-interface",
""
] |
I run a couple of game tunnelling servers and would like to have a page where the client can run a ping on all the servers and find out which is the most responsive. As far as I can see there seems to be no proper way to do this in JavaScript, but I was thinking, does anybody know of a way to do this in flash or some other client browser technology maybe? | Most applet technology, including Javascript, enforces a same-origin policy. It may be possible to dynamically add DOM elements, such as images, and collect timing information using the onload event handler.
Psuedo-code
```
for (server in servers) {
var img = document.createElement('IMG');
server.startTime = getCurrentTimeInMS();
img.onload=function() { server.endTime = getcurrentTimeInMS(); }
img.src = server.imgUrl;
}
```
Then wait an appropriate time and check the timing for each server object. Repeat as needed and compute averages if you want. I'm not sure what kind of accuracy you can expect.
Disadvantages:
* You are probably using the wrong tool for the job. A browser is not equipped for this sort of application.
* It's probably quite inaccurate.
* If the resource you request is cached it won't give you the results you want, but you can work around that by changing the url each time.
* This is bandwidth-intensive compared to a normal ping. Make the image tiny, such as a spacer.gif file.
* The timing depends not only on the latency of the remote server but the bandwidth of that server. This may be a more or less useful measure but it's important to note that it is not simply the latency.
* You need to be able to serve HTTP requests from the various servers and, crucially, each server should serve the exact same resource (or a resource of the same length). Conditions on the server can affect the response time, such as if one server is compressing the data and another isn't. | Before the call to the server, record the Javascript time:
```
var startTime = new Date();
```
Load an image from the server:
```
var img = new Image()
img.onload = function() {
// record end time
}
img.src = "http://server1.domain.com/ping.jpg";
```
As soon as the request is finished, record the time again. (Given of course that the request didn't time out.)
```
var endTime = new Date();
```
Your ping in milliseconds is:
```
var ping = endTime. getTime() - startTime.getTime();
``` | How to determine latency of a remote server through the browser | [
"",
"javascript",
"flash",
"browser",
"latency",
"ping",
""
] |
I wanted to set some handler for all the unexpected exceptions that I might not have caught inside my code. In `Program.Main()` I used the following code:
```
AppDomain.CurrentDomain.UnhandledException
+= new UnhandledExceptionEventHandler(ErrorHandler.HandleException);
```
But it didn't work as I expected. When I started the application in debugging mode and threw an exception it did call the handler, but afterwards the exception helper in Visual Studio popped up as if the exception occurred without any handling. I tried Application.Exit() inside the handler but it didn't work as well.
What I would like to achieve is that the exception is handled with my handler and then the application closes nicely. Is there any other way to do it or am I using the code above in the wrong way? | It's because you're running it through Visual Studio in Debug mode. If you release and install your app somewhere else, nothing but your global exception handler will be processed. | Normally I use something like this to try and catch all unexpected top-level exceptions.
```
using System;
static class Program
{
[STAThread]
static void Main(string[] argv)
{
try
{
AppDomain.CurrentDomain.UnhandledException += (sender,e)
=> FatalExceptionObject(e.ExceptionObject);
Application.ThreadException += (sender,e)
=> FatalExceptionHandler.Handle(e.Exception);
// whatever you need/want here
Application.Run(new MainWindow());
}
catch (Exception huh)
{
FatalExceptionHandler.Handle(huh);
}
}
static void FatalExceptionObject(object exceptionObject) {
var huh = exceptionObject as Exception;
if (huh == null) {
huh = new NotSupportedException(
"Unhandled exception doesn't derive from System.Exception: "
+ exceptionObject.ToString()
);
}
FatalExceptionHandler.Handle(huh);
}
}
```
Maybe it is something you find helpful too? This main code routes all three ways of catching unexpected top-level exceptions through one method call. All you now need is a static class `FatalExceptionHandler` that includes your top-level exception handling in its `Handle` method.
And really, any application developer knows there are really just two things to do there:
1. Show/log the exception like you see fit
2. Make sure you exit/kill the application process
If you think item two is strange, remember that we only bother to do this in the first place for really exceptional situations. These things are probably bugs that need changes to your application to be accurately addressed. Any other exception handling - the functional kind - should be lower down inside your actual program code, catching specific kinds of exceptions where this makes sense and handling them there in the way that makes sense. Anything else should bubble up to your `FatalExceptionHandler` to make itself known and stop the possibly crippled program from working from corrupted state
Dead programs tell no lies... ;-) | Handling unhandled exceptions problem | [
"",
"c#",
"exception",
""
] |
I'm pulling a row from a database and there is a date field (y-m-d). I need to create an if statement so that I can do something IF that date is longer then 13 days ago. I've already found out how to display all results which are longer then 13 days ago if it is any help.
```
SELECT * FROM links WHERE (TO_DAYS(NOW()) - TO_DAYS(date))>13
```
Any help would be greatly appreciated. | In php you can use:
```
$date = '2008-11-05';
if (strtotime("now") > strtotime("+13 days", strtotime($date))) {
//Do something
}
``` | One way is to convert the y-m-d string to a timestamp, and see if it is larger than 13\*86400 seconds old (86400 = no of seconds in a day)
```
$age=time() - strtotime($date);
if ($age > (13*86400))
{
//do something
}
``` | PHP If Date Is >13 Days Ago | [
"",
"php",
"mysql",
""
] |
If I were to tag a bunch of images via XMP, in Python, what would be the best way? I've used Perl's **Image::ExifTool** and I am very much used to its reliability. I mean the thing never bricked on tens of thousands of images.
I found [this](http://code.google.com/p/python-xmp-toolkit/), backed by some heavy-hitters like the European Space Agency, but it's clearly marked as unstable.
Now, assuming I am comfortable with C++, how easy is it to, say, use the [Adobe XMP toolkit](http://www.adobe.com/devnet/xmp/) directly, in Python? Having never done this before, I am not sure what I'd sign up for.
**Update:** I tried some libraries out there and, including the fore mentioned toolkit, they are still pretty immature and have glaring problems. I resorted to actually writing an Perl-based server that accepts XML requests to read and write metadata, with the combat-tested Image::EXIF. The amount of code is actually very light, and definitely beats torturing yourself by trying to get the Python libraries to work. The server solution is language-agnostic, so it's a twofer. | Well, they website says that the python-xmp-toolkit uses Exempi, which is based on the Adobe XMP toolkit, via ctypes. What I'm trying to say is that you're not likely to create a better wrapping of the C++ code yourself. If it's unstable (i.e. buggy), it's most likely still cheaper for you to create patches than doing it yourself from scratch.
However, in your special situation, it depends on how much functionality you need. If you just need a single function, then wrapping the C++ code into a small C extension library or with Cython is feasible. When you need to have all functionality & flexibility, you have to create wrappers manually or using SWIG, basically repeating the work already done by other people. | I struggled for several hours with python-xmp-toolkit, and eventually gave up and just wrapped calls to [ExifTool](http://www.sno.phy.queensu.ca/~phil/exiftool/).
There is [a Ruby library](http://miniexiftool.rubyforge.org/) that wraps ExifTool as well (albeit, much better than what I created); I feel it'd be worth porting it to Python for a simple way of dealing with XMP. | XMP image tagging and Python | [
"",
"python",
"xmp",
""
] |
We were given a sample document, and need to be able to reproduce the structure of the document exactly for a vendor. However, I'm a little lost with how C# handles namespaces. Here's a sample of the document:
```
<?xml version="1.0" encoding="UTF-8"?>
<Doc1 xmlns="http://www.sample.com/file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sample.com/file/long/path.xsd">
<header>
<stuff>data</stuff>
<morestuff>data</morestuff>
</header>
</Doc1>
```
How I'd usually go about this is to load a blank document, and then start populating it:
```
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Doc1></Doc1>");
// Add nodes here with insert, etc...
```
Once I get the document started, how do I get the namespace and schema into the Doc1 element? If I start with the namespace and schema in the Doc1 element by including them in the LoadXml(), then *all* of the child elements have the namespace on them -- and that's a no-no. The document is rejected.
So in other words, I have to produce it EXACTLY as shown. (And I'd rather not just write text-to-a-file in C# and hope it's valid XML). | You should try it that way
```
XmlDocument doc = new XmlDocument();
XmlSchema schema = new XmlSchema();
schema.Namespaces.Add("xmlns", "http://www.sample.com/file");
doc.Schemas.Add(schema);
```
Do not forget to include the following namespaces:
```
using System.Xml.Schema;
using System.Xml;
``` | I personally prefer to use the common XmlElement and its attributes for declaring namespaces. I know there are better ways, but this one never fails.
Try something like this:
```
xRootElement.SetAttribute("xmlns:xsi", "http://example.com/xmlns1");
``` | Creating a specific XML document using namespaces in C# | [
"",
"c#",
"xml",
"namespaces",
"xsd",
""
] |
I'm very new to ASP.NET, help me please understand MasterPages conception more.
I have Site.master with common header data (css, meta, etc), center form (blank) and footer (copyright info, contact us link, etc).
```
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="_SiteMaster" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="tagHead" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<form id="frmMaster" runat="server">
<div>
<asp:ContentPlaceHolder ID="holderForm" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="holderFooter" runat="server">Some footer here</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
```
and I want to use second master page for a project into sub directory, which would contains SQL query on Page\_Load for logging (it isn't necessary for whole site).
```
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Project.master.cs" Inherits="_ProjectMaster" MasterPageFile="~/Site.master" %>
<asp:Content ContentPlaceHolderID="holderForm" runat="server">
<asp:ContentPlaceHolder ID="holderForm" runat="server" EnableViewState="true"></asp:ContentPlaceHolder>
</asp:Content>
<asp:Content ContentPlaceHolderID="holderFooter" runat="server">
<asp:ContentPlaceHolder ID="holderFooter" runat="server" EnableViewState="true"></asp:ContentPlaceHolder>
</asp:Content>
```
But I have a problem: footer isn't displayed.
**Where is my mistake? Am I right to use second master page as super class for logging?**
Project page looks like this:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" MasterPageFile="~/Project.master" %>
<asp:Content ContentPlaceHolderID="holderForm" runat="server">
<p>Hello World!</p>
</asp:Content>
<asp:Content ContentPlaceHolderID="holderFooter" runat="Server">
Some footer content
</asp:Content>
``` | I've been working with nested master pages and have run in to something similar. From what I see where you have "Some footer here" in the Site.Master is where the problem lies and I've had similar problems with having content with-in a contentplaceholder tag. if you try this instead
```
<asp:ContentPlaceHolder ID="holderFooter" runat="server"/>Some footer here
```
Then you should be able to see the footer content. | I'm not sure I'd use master pages for this. If it's really just going to do logging, I'd implement IHttpModule, register it in web.config, and then check whether or not to log based on the path of the request. I think of master pages as being about *content* rather than other processing such as logging.
See the [IHttpModule walkthrough](http://msdn.microsoft.com/en-us/library/ms227673.aspx) on MSDN for an example - in your BeginRequest handler, you'd probably check the request path and log appropriately if it matched.
Apologies if I misunderstood what you're trying to do though. | Using nested Master Pages | [
"",
"c#",
"asp.net",
"inheritance",
"master-pages",
"nested",
""
] |
I'm working on an application that gets content from feeds in C#. This content should then be displayed on the form.
My question is what control should I use to hold this data? Should I be creating a new label (dynamically) for each item? Someone suggested to me that I should use a RichTextBox but this content shouldn't be editable.
If it helps, I'm a web developer. I'd normally output my content in HTML and would use headings, paragraphs etc. for my content. Am I looking at this the wrong way?
If this seems like a very basic question, it probably is. I'm very new to Windows Forms.
Thanks,
Ross | DataGridView is good enough for this. See this example. Of course you can improve on look and feel :)
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<Item> items = new List<Item>();
items.Add(new Item("item 1"));
items.Add(new Item("item 2"));
items.Add(new Item("item 3"));
items.Add(new Item("item 4"));
dataGridView1.DataSource = items;
}
}
class Item
{
public string ItemName { get; set; }
public Item(string name)
{
ItemName = name;
}
}
``` | If you're comfortable with HTML, I'd say go with a WebBrowser control. It's easy to use, you're familiar with HTML, so you can have complete control over what you want to display. No use in trying to reinvent the wheel.
EDIT: If you strictly want to stick with Winforms though, and feel a WebBrowser won't cut it, I'd probably suggest a DataGridView. You can host all kinds of content in there as well as images and links, and you can turn off all kinds of editing. You can even get rid of the grid lines, so it won't have the "look" of a grid. | Dynamic content in windows forms | [
"",
"c#",
"winforms",
""
] |
I'm trying to decipher CHtmlView's behaviour when files are dragged into the client area, so I've created a new MFC app and commented out the CHtmlView line that navigates to MSDN on startup. In my main frame, I've overridden CWnd::OnDropFiles() with a function that shows a message box, to see when WM\_DROPFILES is sent.
OnDropFiles() gets triggered on all except the first time you try to drag a file into the application. Uniquely, that first time appears to be interpreted by the application as a request to display the data in the file rather than a request to open the file. I've tried overriding OnDrop() from the view class, but it's never called.
Why is the first time different? How can I catch all attempts to drag a file into my app? | This is part of the underlying `WebBrowser` control behaviour. `CHtmlView` sets `RegisterAsDropTarget` to `true` by default, which means the control intercepts the drop operation and performs its own processing.
If you want to inhibit it, call `SetRegisterAsDropTarget(FALSE)` in your `OnInitialUpdate` implementation. All drop operations will then interact with the main window. | Preface: I'm extrapolating from documentation I've found, and am not concerned if I'm wrong. Please make sure the following explanation makes sense, ie try it, before voting-up my answer or accepting it :)
After Googling `OnDropFiles`, I discovered that it's inherited from the `CWnd` class: [(MSDN page)](http://msdn.microsoft.com/en-us/library/62zys01d(VS.80).aspx)
---
According to that MSDN article:
**Parameters**
`hDropInfo`
> A pointer to an internal data structure that describes the dropped files. This handle is used by the `DragFinish`, `DragQueryFile`, and `DragQueryPoint` Windows functions to retrieve information about the dropped files.
Quoting later:
> "The framework calls this member function when the user releases the left mouse button over a window that has registered itself as the recipient of dropped files.
>
> "Typically, a derived class will be designed to support dropped files and it will register itself during window construction.
>
> This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function."
---
That *appears* to indicate that until the function has been registered, it won't work 'as expected'.
Therefore, I believe that what's happening is that the first time you drop something onto the CHTMLView, it registers itself, and only ***then*** 'works as expected'.
If my understanding is correct, then a new question is raised, which is how can you force the registration of the View. From the related links on the MSDN Technote, it looks like you can force `DragAcceptFiles` [(see here)](http://msdn.microsoft.com/en-us/library/bb776406(VS.85).aspx) to run, which would otherwise be triggered when the drop event finished. | How can you make an MFC application with an HTML view consistently accept drag-dropped files? | [
"",
"c++",
"mfc",
""
] |
How can you check to see if a user can execute a stored procedure in MS SQL server?
I can see if the user has explicit execute permissions by connecting to the master database and executing:
```
databasename..sp_helpprotect 'storedProcedureName', 'username'
```
however if the user is a member of a role that has execute permissions sp\_helprotect won't help me.
Ideally I'd like to be able to call something like
```
databasename..sp_canexecute 'storedProcedureName', 'username'
```
which would return a bool. | [`fn_my_permissions`](http://msdn.microsoft.com/en-us/library/ms176097.aspx) and [`HAS_PERMS_BY_NAME`](http://msdn.microsoft.com/en-us/library/ms189802.aspx) | Try something like this:
```
CREATE PROCEDURE [dbo].[sp_canexecute]
@procedure_name varchar(255),
@username varchar(255),
@has_execute_permissions bit OUTPUT
AS
IF EXISTS (
/* Explicit permission */
SELECT 1
FROM sys.database_permissions p
INNER JOIN sys.all_objects o ON p.major_id = o.[object_id] AND o.[name] = @procedure_name
INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id AND dp.[name] = @username
)
OR EXISTS (
/* Role-based permission */
SELECT 1
FROM sys.database_permissions p
INNER JOIN sys.all_objects o ON p.major_id = o.[object_id]
INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id AND o.[name] = @procedure_name
INNER JOIN sys.database_role_members drm ON dp.principal_id = drm.role_principal_id
INNER JOIN sys.database_principals dp2 ON drm.member_principal_id = dp2.principal_id AND dp2.[name] = @username
)
BEGIN
SET @has_execute_permissions = 1
END
ELSE
BEGIN
SET @has_execute_permissions = 0
END
GO
``` | MS SQL Server: Check to see if a user can execute a stored procedure | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"stored-procedures",
""
] |
What would be the best way to look in a `string[]` to see if it contains a element. This was my first shot at it. But perhaps there is something that I am overlooking. The array size will be no larger than 200 elements.
```
bool isStringInArray(string[] strArray, string key)
{
for (int i = 0; i <= strArray.Length - 1; i++)
if (strArray[i] == key)
return true;
return false;
}
``` | Just use the already built-in Contains() method:
```
using System.Linq;
//...
string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
//...
}
``` | I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.
You can read my [blog post](http://www.thecodepage.com/post.aspx?id=28197601-0cae-48a2-aadf-992e073f8690) to see more information about how to do this, but the main idea is this:
By adding this extension method to your code:
```
public static bool IsIn<T>(this T source, params T[] values)
{
return values.Contains(source);
}
```
you can perform your search like this:
```
string myStr = "str3";
bool found = myStr.IsIn("str1", "str2", "str3", "str4");
```
It works on any type (as long as you create a good equals method). Any value type for sure. | Is string in array? | [
"",
"c#",
"arrays",
"string",
""
] |
```
########################################
# some comment
# other comment
########################################
block1 {
value=data
some_value=some other kind of data
othervalue=032423432
}
block2 {
value=data
some_value=some other kind of data
othervalue=032423432
}
``` | The best way would be to use an existing format such as JSON.
Here's an example parser for your format:
```
from lepl import (AnyBut, Digit, Drop, Eos, Integer, Letter,
NON_GREEDY, Regexp, Space, Separator, Word)
# EBNF
# name = ( letter | "_" ) , { letter | "_" | digit } ;
name = Word(Letter() | '_',
Letter() | '_' | Digit())
# words = word , space+ , word , { space+ , word } ;
# two or more space-separated words (non-greedy to allow comment at the end)
words = Word()[2::NON_GREEDY, ~Space()[1:]] > list
# value = integer | word | words ;
value = (Integer() >> int) | Word() | words
# comment = "#" , { all characters - "\n" } , ( "\n" | EOF ) ;
comment = '#' & AnyBut('\n')[:] & ('\n' | Eos())
with Separator(~Regexp(r'\s*')):
# statement = name , "=" , value ;
statement = name & Drop('=') & value > tuple
# suite = "{" , { comment | statement } , "}" ;
suite = Drop('{') & (~comment | statement)[:] & Drop('}') > dict
# block = name , suite ;
block = name & suite > tuple
# config = { comment | block } ;
config = (~comment | block)[:] & Eos() > dict
from pprint import pprint
pprint(config.parse(open('input.cfg').read()))
```
Output:
```
[{'block1': {'othervalue': 32423432,
'some_value': ['some', 'other', 'kind', 'of', 'data'],
'value': 'data'},
'block2': {'othervalue': 32423432,
'some_value': ['some', 'other', 'kind', 'of', 'data'],
'value': 'data'}}]
``` | Well, the data looks pretty regular. So you could do something like this (untested):
```
class Block(object):
def __init__(self, name):
self.name = name
infile = open(...) # insert filename here
current = None
blocks = []
for line in infile:
if line.lstrip().startswith('#'):
continue
elif line.rstrip().endswith('{'):
current = Block(line.split()[0])
elif '=' in line:
attr, value = line.strip().split('=')
try:
value = int(value)
except ValueError:
pass
setattr(current, attr, value)
elif line.rstrip().endswith('}'):
blocks.append(current)
```
The result will be a list of Block instances, where `block.name` will be the name (`'block1'`, `'block2'`, etc.) and other attributes correspond to the keys in your data. So, `blocks[0].value` will be 'data', etc. Note that this only handles strings and integers as values.
(there is an obvious bug here if your keys can ever include 'name'. You might like to change `self.name` to `self._name` or something if this can happen)
HTH! | What's the best way(error proof / foolproof) to parse a file using python with following format? | [
"",
"python",
"text-parsing",
""
] |
I am receiving packets sent to my server through UDP. I am using socket\_read to read the data and it is coming along just fine. I have run into an error however. The length parameter to socket\_read in my case is NOT always the same. The length of the data can range anywhere from 50-150 bytes. One thing that remains constant is that the data set is ended with a \x00 byte. How would I get the read function to always read until encountering this byte? I have already tried PHP\_NORMAL\_READ flag, but the docs say it only ends at \n or \r which really isn't what I want (tried it it doesn't work for my data). At the same time, the php page for socket\_read states in the *length* parameter description that,
> The maximum number of bytes read is
> specified by the length parameter.
> Otherwise you can use \r, \n, or \0 to
> end reading (depending on the type
> parameter, see below).
The type says nothing about the /0 byte. Its like a piece of documentation is missing. What I need is a function that will either let me specify a delimiter for my data, will automatically read all the data from the socket that is available. There might be a solution in the socket\_recv function but its undocumented and I don't know how it works.
Thanks in advance. | If I understand correctly, you want to read data from a socket until there is no more data to read, with the problem being that the amount of data is variable and you don't know when to stop.
According to the relevant manual page (<http://php.net/socket_read>):
> Note: socket\_read() returns a zero
> length string ("") when there is no
> more data to read.
You should be able to deal with variable-length data by reading byte-by-byte until you hit a zero-length string:
```
while (($currentByte = socket_read($socket, 1)) != "") {
// Do whatever you wish with the current byte
}
``` | Hav you tried something like this:
```
do {
echo socket_read($handle,1024);
$status = socket_get_status($handle);
} while($status['unread_bytes']);
``` | variable length packets in php | [
"",
"php",
"sockets",
""
] |
I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5.
I'm sure there is very easy way of doing this - I just don't know how. | Just call [Math.abs](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-). For example:
```
int x = Math.abs(-5);
```
Which will set `x` to `5`.
Note that if you pass `Integer.MIN_VALUE`, the same value (still negative) will be returned, as the range of `int` does not allow the positive equivalent to be represented. | The concept you are describing is called "absolute value", and Java has a function called [Math.abs](http://java.sun.com/javase/6/docs/api/java/lang/Math.html#abs(int)) to do it for you. Or you could avoid the function call and do it yourself:
```
number = (number < 0 ? -number : number);
```
or
```
if (number < 0)
number = -number;
``` | Make a negative number positive | [
"",
"java",
"negative-number",
""
] |
Is creating an index for a column that is being summed is faster than no index? | Sorry, it is not clear what you are asking.
Are you asking, would it speed up a query such as
```
SELECT product, sum(quantity) FROM receipts
GROUP BY product
```
if you added an index on quantity?
If that is the question, then the answer is no. Generally speaking, indexes are helpful when you need to find just a few rows among many; here you need all rows, so an index does not help.
There is an obscure exception (which applies so rarely most DB optimizers probably don't bother implementing this trick). If your query happens to be
```
SELECT sum(foo) FROM bar
```
, where there is an index on foo, and bar is a table with many columns, it is possible to read in the full index, incurring a smaller hit than if you read the underlying table, and get the answer directly from the index -- never having to touch the "real" table at all! This is a fairly rare case, however, and you will want to test that your optimizer knows to do this before relying on this too much. | No. Indexes improve searches by limiting how many checks are required. An aggregate function (count, max, min, sum, avg) has to run through all the entries in a column regardless. | Index a sum column | [
"",
"mysql",
"sql",
"sql-server",
"indexing",
"sum",
""
] |
I have two classes:
```
public class MyBase
{
public virtual void DoMe()
{
}
}
public class MyDerived:MyBase
{
public override void DoMe()
{
throw new NotImplementedException();
}
}
```
And I have the following code to instantiate MyDerived:
```
MyDerived myDerived=new MyDerived();
```
The thing is how to call DoMe of the base class? If I use myDerived.DoMe(), then the derived method wil be called, resulting in an exception. I tried to cast myDerived to MyBase, yet it is still the derived version of the method that gets called.
***Edit: As mentioned in the below comment, I can't change eitehr MyDerived or MyBase because they are not my code.*** | There's a solution, but it's ugly: use reflection to get the base-class method, and then emit the IL necessary to call it. Check out [this blog post](http://kennethxu.blogspot.com/2009/05/strong-typed-high-performance.html) which illustrates how to do this. I've successfully used this approach it to call the base class's implementation of a method when all I have is a reference to a derived class which overrides that method. | You can't call the base-class version.
If the method doesn't work on the derived class, then it's rather unlikely the base version of the method will work when called on an instance of the derived class. That's just asking for trouble. The class was not designed to work that way, and what you're trying to do will probably just cause other parts of the class to behave unpredictably.
Why do you need to call this method on the object when the object tells you outright that it won't work?
It seems to me that these classes have some design flaws, and if you're not allowed to change the classes, maybe you're allowed to change to a more well designed library instead. | Force calling the base method from outside a derived class | [
"",
"c#",
"inheritance",
"overriding",
""
] |
I need to have PHP authenticate to an exchange server. Once able to succesfully connect to it, I'll need to write webdav requests in the PHP so I can extract data from the exchange server and use it in a web application.
It would be somewhat simple except that the 2003 Exchange server has Forms Based Authentication (FBA) turned on. With FBA turned on I believe I'm suppose to do what the below (see link) blog article says. My problem is that I need help converting his instructions for ASP into PHP.
<http://blogs.msdn.com/webdav_101/archive/2008/12/12/webdav-fba-authentication-sample-explained.aspx>
Does anybody understand the details of what he's describing on this article? Any insight would help.
More specific info if needed: I'm confused as to how to configure the POST request (I mean, when you normally POST data to a form, don't you usually load the page your posting to? In his instructions he says to POST it to /exchweb/bin/auth/owaauth.dll . How does this work?)
I'm also confused as to how to do the 3rd step listed: 3) WebReq.KeepAlive and AllowAutoRedirect should be set to True on the request.
On top of that, I could really use some help detailing how to take the post data and put it in a cookie in PHP.
Thanks in advance for any help provided! | I believe the best way to do this is via curl. (<http://ca.php.net/curl>)
On the page linked, the first example is a good class to use (I've used it to auto-login into other websites)
It should have KeepAlive (header) and Redirect on by default (`curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);` )
You'll need to ensure the webservice can create/modify cookie.txt then try:
```
$cc = new cURL();
$cc->post('http://www.yourexchange.com','destination=https%3A%2F%2F' . $strServerName . '%2Fexchange%2F' . $strUserName . '%2F&username=' . $strDomain . '%5C' . $strUserName . '&password=' . $strPassword . '&SubmitCreds=Log+On&forcedownlevel=0&trusted=0');
```
The above is a quick translation from the info on the page you linked to, you may need to use urlencode() on your variables if there are special characters. Once the above successfully works you can use
```
$page=$cc->get('http://www.yourexchange.com/?whatever=youneed');
```
The $page will contain the string result from the get (it sends the cookie stored in the text file on this request) then you can use regular expression to get what you need.
This should get you very close to what you need. | It looks like the text file is actually named "cookies.txt". You can create a blank text file with this name and upload it to the same directory. In your ftp client you should be able to set permissions, I believe 777 is the permission code you'll need. If you can't just enter the permission code try checking all boxes to give all permissions.
re: last post,
that is correct, where the script runs it is basically a client and the cookie file is a simple way of storing the cookie for easy re-use. | How do I do this ASP WebDAV FBA Authentication example in PHP? | [
"",
"php",
"exchange-server",
"webdav",
""
] |
Whenever I install Visual Studio 2005 or 2008 and choose the C# profile, the "News" portion of the start page defaults to "<http://go.microsoft.com/fwlink/?linkid=45192&clcid=409>".
I like the start page and like to reference it and like the content of the default MSDN C# news feed (there is a lot of good stuff there) provided, but the feed hasn't been updated since March 2008.
**Is there a more up to date MSDN C# News feed?** This one is titled "MSDN: Visual C#" and subtitled "The latest information for developers on Visual C#" leading me to think it is the appropriate "official" MS C# news feed. **Or, is this just a dummy feed MS throws in and developers are expected to customize their VS start page with their preferred feeds?** I don't have a problem doing that - I just thought the one provided looked promising (if it was up to date). | I would just change the feed to whatever suits you, and whatever is most interesting to you. There are several sites that can [combine several feeds into one](http://ask.metafilter.com/16678/Combine-RSS-feeds-into-new-feed), and that might also be a good option. | So I realize this is an ancient thread now, but I happened across it searching for the same thing. I recently installed VS2008 on a second machine, and the URL it is using *has* been updated (as recently as 12/08/2009, and is:
<http://go.microsoft.com/fwlink/?linkid=84795&clcid=409>
Cheers! | Default News Feed on Visual Studio Start Page (C# Profile) | [
"",
"c#",
"visual-studio",
""
] |
How can I measure number of lines of code in my PHP web development projects?
Edit: I'm interested in windows tools only | If you're using a full fledged IDE the quick and dirty way is to count the number of "\n" patterns using the search feature (assuming it supports regexes) | Check [CLOC](http://cloc.sourceforge.net/), it's a source code line counter that supports many languages, I always recommend it.
It will differentiate between actual lines of code, blank lines or comments, it's very good.
In addition there are more code counters that you can check:
* [SLOCCount](http://www.dwheeler.com/sloccount/)
* [sclc](http://www.dwheeler.com/sloccount/)
* USC's [CODECOUNT](http://sunset.usc.edu/research/CODECOUNT/)
* [loc](http://freshmeat.net/projects/loc/)
* [Ohcount](http://labs.ohloh.net/ohcount) | How to measure # of lines of code in project? | [
"",
"php",
"metrics",
"line-count",
""
] |
my main language is vb/c#.net and I'd like to make a console program but with a menu system.
If any of you have worked with "dos" like programs or iSeries from IBM then thats the style I am going for.
 so, was wondering if anyone knows of a "winforms" library that will make my form look like this. I dont mind a "fake winforms look" or a console application but thats how I'd like. | You are looking for a curses like library but for windows. And usable from VB & C#.
Curses provides for a even richer text based UI than even iSeries. All sorts of widgetry!
Windows is not really supportive of text interfaces whether on purpose or not so are out of luck.
But ...
Well, how about [MonoCurses](http://www.mono-project.com/MonoCurses)? I don't know if it will work though. Also look at [PDCurses](http://pdcurses.sourceforge.net/).
And if you don't mind using Python for just the front-end see [this](http://effbot.org/zone/console-index.htm). | I've used iSeries extensively and I remember exactly what you're talking about. To simulate this look and feel in a C# app, you'll want to create a console project and write text to different areas of the screen with the help of the `Console.CursorTop` and `Console.CursorLeft` properties, then calling `Console.Write` or `Console.WriteLine` to write out the text in the previously set position. To change colors, before calling `WriteLine` you'll want to use the `Console.ForegroundColor` and `Console.BackgroundColor` properties.
You'll need to listen for input and upon finding a tab character, your program can use its own internal logic to determine where the cursor should appear next (on the next line in the same column, for instance, to simulate those left columns of input fields in your screenshot).
Doing this with a Windows Forms app will be a little trickier and you'd definitely want to write your own control for it (possibly sub-classed from one of the many types of standard multi-line text controls already available). | creating iSeries like programs | [
"",
"c#",
"ibm-midrange",
""
] |
According to the [Java Language Sepecification](http://docs.oracle.com/javase/specs/), 3rd edition:
> [It is a compile-time error if a generic class is a direct or indirect subclass of `Throwable`.](http://docs.oracle.com/javase/specs/jls/se6/html/classes.html#303584)
I wish to understand why this decision has been made. What's wrong with generic exceptions?
(As far as I know, generics are simply compile-time syntactic sugar, and they will be translated to `Object` anyway in the `.class` files, so effectively declaring a generic class is as if everything in it was an `Object`. Please correct me if I'm wrong.) | As mark said, the types are not reifiable, which is a problem in the following case:
```
try {
doSomeStuff();
} catch (SomeException<Integer> e) {
// ignore that
} catch (SomeException<String> e) {
crashAndBurn()
}
```
Both `SomeException<Integer>` and `SomeException<String>` are erased to the same type, there is no way for the JVM to distinguish the exception instances, and therefore no way to tell which `catch` block should be executed. | It's essentially because it was designed in a bad way.
This issue prevents clean abstract design e.g.,
```
public interface Repository<ID, E extends Entity<ID>> {
E getById(ID id) throws EntityNotFoundException<E, ID>;
}
```
The fact that a catch clause would fail for generics are not reified is no excuse for that.
The compiler could simply disallow concrete generic types that extend Throwable or disallow generics inside catch clauses. | Why doesn't Java allow generic subclasses of Throwable? | [
"",
"java",
"generics",
"exception",
"language-design",
""
] |
I have a list of objects and I want to reorder them randomly on each request. What is the best way of doing this? | How about some kind of [Knuth-Fisher-Yates shuffle algorithm](http://en.wikipedia.org/wiki/Knuth_shuffle) ?
```
for (int i = cards.Length - 1; i > 0; i--)
{
int n = rand.Next(i + 1);
Swap(ref cards[i], ref cards[n]);
}
```
Code taken from [Coding Horror](http://www.codinghorror.com/blog/archives/001015.html). This is also a recommended reading on how people often do this wrong. | Check out this cool Linq way of doing it:
```
public class Employee
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
```
Populate a list:
```
List<Employee> list = new List<Employee>();
list.Add(new Employee { Id = 1, Name = "Davolio Nancy" });
list.Add(new Employee { Id = 2, Name = "Fuller Andrew" });
list.Add(new Employee { Id = 3, Name = "Leverling Janet" });
list.Add(new Employee { Id = 4, Name = "Peacock Margaret" });
list.Add(new Employee { Id = 5, Name = "Buchanan Steven" });
list.Add(new Employee { Id = 6, Name = "Suyama Michael" });
list.Add(new Employee { Id = 7, Name = "King Robert" });
list.Add(new Employee { Id = 8, Name = "Callahan Laura" });
list.Add(new Employee { Id = 9, Name = "Dodsworth Anne" });
```
Then sort:
```
list = list.OrderBy(emp => Guid.NewGuid()).ToList();
```
[Credit](http://www.dailycoding.com/Posts/random_sort_a_list_using_linq.aspx) | What is the best way of randomly re-arranging a list of items in c#? | [
"",
"c#",
".net",
"random",
""
] |
What is the equivalent of a 'friend' keyword in C Sharp?
How do I use the 'internal' keyword?
I have read that 'internal' keyword is a replacement for 'friend' in C#.
I am using a DLL in my C# project that I have the source code for and yet I do not want to modify the existing code. I have inherited the class and I can use my inherited class any way I want. The problem is that most of the code in the parent class has protected methods. Will using a friend somehow make it possible to access or call these protected methods? | 1. You can use the keyword access modifier [`internal`](http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx) to declare a type or type member as accessible to code in the same assembly only.
2. You can use the [`InternalsVisibleToAttribute`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) class defined in [`System.Rutime.CompilerServices`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.aspx) to declare a type as accessible to code in the same assembly or a specified assembly only.
You use the first as you use any other [access modifier](http://msdn.microsoft.com/en-us/library/ms173121.aspx) such as `private`. To wit:
```
internal class MyClass {
...
}
```
You use the second as follows:
```
[assembly:InternalsVisibleTo("MyFriendAssembly", PublicKey="...")]
internal class MyVisibleClass {
...
}
```
Both of these can rightly be considered the equivalent of `friend` in C#.
Methods that are [`protected`](http://msdn.microsoft.com/en-us/library/bcd5672a.aspx) are already available to derived classes. | No, "internal" is not the same as "friend" (at least the C++ 'friend')
friend specifies that this class is only accessible by ONE, particular class.
internal specifies that this class is accessible by ANY class in the assembly. | What is the equivalent of a 'friend' keyword in C Sharp? | [
"",
"c#",
"friend",
"internal",
"friend-class",
""
] |
It seems they canceled in Python 3 all the easy ways to quickly load a script by removing `execfile()`.
Is there an obvious alternative I'm missing? | [According to the documentation](https://docs.python.org/3.3/whatsnew/3.0.html?highlight=execfile#builtins), instead of
```
execfile("./filename")
```
Use
```
exec(open("./filename").read())
```
See:
* [What’s New In Python 3.0](http://docs.python.org/3.3/whatsnew/3.0.html?highlight=execfile#builtins)
* [`execfile`](https://docs.python.org/2/library/functions.html?highlight=exec#execfile)
* [`exec`](https://docs.python.org/3/library/functions.html?highlight=exec#exec) | You are just supposed to read the file and exec the code yourself. 2to3 current replaces
```
execfile("somefile.py", global_vars, local_vars)
```
as
```
with open("somefile.py") as f:
code = compile(f.read(), "somefile.py", 'exec')
exec(code, global_vars, local_vars)
```
(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)
See:
* <http://docs.python.org/release/2.7.3/library/functions.html#execfile>
* <http://docs.python.org/release/3.2.3/library/functions.html#compile>
* <http://docs.python.org/release/3.2.3/library/functions.html#exec> | What is an alternative to execfile in Python 3? | [
"",
"python",
"python-3.x",
""
] |
So i am building an application that will have lots of windows, all with the same basic layout:
1. A main Window
2. A logo in the top corner
3. A title block
4. A status displayer down the bottom
5. An area for window specific controls.
At the moment i have to recreate this structure in every window. Ideally i want this layout to be coded in a single place, perhaps into a custom Window subclass for ease of use. Does anyone have any clues for how to get started, or previous experience with similar problems? | You can create a new ControlTemplate that targets a window to accomplish this as shown below.
```
<ControlTemplate x:Key="WindowControlTemplate1" TargetType="{x:Type Window}">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="0.93*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.21*"/>
<ColumnDefinition Width="0.79*"/>
</Grid.ColumnDefinitions>
<ContentPresenter
Grid.ColumnSpan="2"
Grid.Row="1"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
/>
<ResizeGrip
HorizontalAlignment="Right"
x:Name="WindowResizeGrip"
VerticalAlignment="Bottom"
IsTabStop="False"
Visibility="Collapsed"
Grid.Column="1"
Grid.Row="2"
/>
<TextBlock Text="My Logo" />
<TextBlock Grid.Column="1" Text="My Title"/>
<StatusBar Height="20" Grid.ColumnSpan="2" Grid.Row="2"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode" Value="CanResizeWithGrip"/>
<Condition Property="WindowState" Value="Normal"/>
</MultiTrigger.Conditions>
<Setter Property="Visibility" TargetName="WindowResizeGrip" Value="Visible"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
``` | If you're brave enough to take a big architectural shift you could consider [CompositeWPF](http://www.microsoft.com/CompositeWPF) (previously codenamed Prism) from the Patterns & Practices guys at Microsoft.
Of interest to you would be the ability to define "regions" in a shell (i.e. window) and then using views to fill the regions. It uses the Model-View-Presenter pattern to allow independent development of "views" from the model than can be easily be relocated over time as the shell only defines regions and is not coupled directly to what is placed in to it. Principally this helps decouple the shell from the views and the views from each other and make it easier to unit-test ... blah, blah blah.
It is a big jump and something that will slow you down to begin with, although your situation is one of the types of applications that CompositeWPF is meant to address.
As part of CompositeWPF you will need to take on board various patterns that can confuse newcomers, e.g. The UnityContainer, inversion-of-control, MVP (or Model/view/view-model) and dependency injection.
I can remember when I first started with the sample apps being puzzled because it is not obvious how on earth the some of the views were even being created! The unity container will instantiate objects and call parameterised constructors magically.
CompositeWPF is an elegant solution to your question but not a simple or straightforward one. Having used CompositeWPF in my last project I intend to use it again for the next appropriate application. | How to make a Template Window in WPF? | [
"",
"c#",
"wpf",
"wpf-controls",
""
] |
I have a query like this:
```
SELECT t1.id,
(SELECT COUNT(t2.id)
FROM t2
WHERE t2.id = t1.id
) as num_things
FROM t1
WHERE num_things = 5;
```
The goal is to get the id of all the elements that appear 5 times in the other table. However, I get this error:
```
ERROR: column "num_things" does not exist
SQL state: 42703
```
I'm probably doing something silly here, as I'm somewhat new to databases. Is there a way to fix this query so I can access `num_things`? Or, if not, is there any other way of achieving this result? | I think you could just rewrite your query like so:
```
SELECT t1.id
FROM t1
WHERE (SELECT COUNT(t2.id)
FROM t2
WHERE t2.id = t1.id
) = 5;
``` | A few important points about using SQL:
* You cannot use column aliases in the WHERE clause, but you can in the HAVING clause. That's the cause of the error you got.
* You can do your count better using a JOIN and GROUP BY than by using correlated subqueries. It'll be much faster.
* Use the HAVING clause to filter groups.
Here's the way I'd write this query:
```
SELECT t1.id, COUNT(t2.id) AS num_things
FROM t1 JOIN t2 USING (id)
GROUP BY t1.id
HAVING num_things = 5;
```
I realize this query can skip the `JOIN` with t1, as in Charles Bretana's solution. But I assume you might want the query to include some other columns from t1.
---
Re: the question in the comment:
The difference is that the `WHERE` clause is evaluated on rows, before `GROUP BY` reduces groups to a single row per group. The `HAVING` clause is evaluated after groups are formed. So you can't, for example, change the `COUNT()` of a group by using `HAVING`; you can only exclude the group itself.
```
SELECT t1.id, COUNT(t2.id) as num
FROM t1 JOIN t2 USING (id)
WHERE t2.attribute = <value>
GROUP BY t1.id
HAVING num > 5;
```
In the above query, `WHERE` filters for rows matching a condition, and `HAVING` filters for groups that have at least five count.
The point that causes most people confusion is when they don't have a `GROUP BY` clause, so it *seems* like `HAVING` and `WHERE` are interchangeable.
`WHERE` is evaluated before expressions in the select-list. This may not be obvious because SQL syntax puts the select-list first. So you can save a lot of expensive computation by using `WHERE` to restrict rows.
```
SELECT <expensive expressions>
FROM t1
HAVING primaryKey = 1234;
```
If you use a query like the above, the expressions in the select-list are computed for *every row*, only to discard most of the results because of the `HAVING` condition. However, the query below computes the expression only for the *single row* matching the `WHERE` condition.
```
SELECT <expensive expressions>
FROM t1
WHERE primaryKey = 1234;
```
So to recap, queries are run by the database engine according to series of steps:
1. Generate set of rows from table(s), including any rows produced by `JOIN`.
2. Evaluate `WHERE` conditions against the set of rows, filtering out rows that don't match.
3. Compute expressions in select-list for each in the set of rows.
4. Apply column aliases (note this is a separate step, which means you can't use aliases in expressions in the select-list).
5. Condense groups to a single row per group, according to `GROUP BY` clause.
6. Evaluate `HAVING` conditions against groups, filtering out groups that don't match.
7. Sort result, according to `ORDER BY` clause. | PostgreSQL - Correlated Sub-Query Fail? | [
"",
"sql",
"database",
"postgresql",
"subquery",
""
] |
What does the last line mean in the following code?
```
import pickle, urllib
handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")
data = pickle.load(handle)
handle.close()
for elt in data:
print "".join([e[1] * e[0] for e in elt])
```
My attempt to the problem:
* "".join... uses join -method to empty text
* e[1] \* e[0] multiplies two subsequent values in the sequence, e
* I am not sure what is e
* I am not sure, what it means, when you have something before for -loop, like: `e[1] * e[0] for e in elt` | Maybe best explained with an example:
```
print "".join([e[1] * e[0] for e in elt])
```
is the short form of
```
x = []
for e in elt:
x.append(e[1] * e[0])
print "".join(x)
```
List comprehensions are simply syntactic sugar for `for` loops, which make an expression out of a sequence of statements.
`elt` can be an arbitrary object, since you load it from pickles, and `e` likewise. The usage suggests that is it a [sequence](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange) type, but it could just be anything that implements the sequence protocol. | Firstly, you need to put http:// in front of the URL, ie:
```
handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p")
```
An expression `[e for e in a_list]` is a [list comprehension](http://en.wikipedia.org/wiki/List_comprehension) which generates a list of values.
With Python strings, the `*` operator is used to repeat a string. Try typing in the commands one by one into an interpreter then look at data:
```
>>> data[0]
[(' ', 95)]
```
This shows us each line of data is a tuple containing two elements.
Thus the expression `e[1] * e[0]` is effectively the string in `e[0]` repeated `e[1]` times.
Hence the program draws a banner. | Problem in understanding Python list comprehensions | [
"",
"python",
"list-comprehension",
""
] |
Is there a library for crating/extracting zip files in php?
The ZipArchive class works erratically, and this is mentioned on php.net :
(for every function I checked)
ZipArchive::addEmptyDir
(No version information available, might be only in CVS) | Ok, I checked <http://pear.php.net/package/Archive_Zip> as posted by Irmantas,
but it says this :
"This package is not maintained anymore and has been superseded. Package has moved to channel pecl.php.net, package zip."
Then I searched pear.php.net and stumbled upon :
<http://pear.php.net/package/File_Archive>
File\_Archive doesn't have a very intuitive set of methods though.
But I wanted simple functionality of making a tar file, and
extracting files from a tar file.
Following snippets achieve that :
Extracting files from a tar file ->
```
<?php
require_once "File/Archive.php";
$tmp = 'output';
$t1 = 'check.tar';
File_Archive::setOption('tmpDirectory','tmp');
$r = File_Archive::extract(
File_Archive::read($t1.'/'),
File_Archive::toFiles($tmp)
);
?>
```
Adding files to a tar file ->
```
<?php
require_once "Archive.php";
$dir = "../../mysql/data/blackStone/";
$files[0] = "";
$i = 0;
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false ) {
if( $file != "." && $file != ".." )
$files[$i++] = $dir.$file;
}
}
File_Archive::extract(
$files,
File_Archive::toArchive(
'check.tar',
File_Archive::toOutput()
)
);
?>
``` | Check PEAR Archive\_Zip it might help you <http://pear.php.net/package/Archive_Zip/docs/latest/Archive_Zip/Archive_Zip.html> | Creating and extracting files from zip archives | [
"",
"php",
"zip",
"archive",
""
] |
I've got a simple java class that looks something like this:
```
public class Skin implements Serializable {
public String scoreFontName = "TahomaBold";
...
public int scoreFontHeight = 20;
...
public int blockSize = 16;
...
public int[] nextBlockX = {205, 205, 205, 205};
...
public String backgroundFile = "back.bmp";
...
}
```
I'd like to read this information from a simple XML file that looks something like this:
```
<xml>
<skin>
<scoreFontName>"Tahoma Bold"</scoreFontName>
...
<scoreFontHeight>20</scoreFontHeight>
...
<blockSize>16</blockSize>
...
<nextBlockX>
<0>205</0>
<1>205</1>
<2>205</2>
<3>205</3>
<nextBlockX>
....
<backgroundFile>"back.bmp"</backgroundFile>
...
<skin>
</xml>
```
Is there an easy way to inject the information from the xml file directly into the variable names rather than having to parse it manually? I don't mind using an external library.
Any help is appreciated. | XStream is really great library for just this.
<http://x-stream.github.io/>
You can set up aliases for your class and even custom data formats to make the XML file more readable. | Alternatives to the already mentioned solutions ([XStream](http://xstream.codehaus.org/) and Apache Commons [Digester](http://commons.apache.org/digester/)) would be Java's own [JAXB](http://jaxb.java.net/) for a comparable general approach, or solutions more tailored towards configuration like Apache Commons [Configuration](http://commons.apache.org/configuration/) or Java's [Preferences API](http://java.sun.com/j2se/1.4.2/docs/guide/lang/preferences.html). | How to easily load a XML-based Config File into a Java Class? | [
"",
"java",
"xml",
"code-injection",
""
] |
A common (i assume?) type of query:
I have two tables ('products', 'productsales'). Each record in 'productsales' represents a sale (so it has 'date', 'quantity', 'product\_id'). How do i efficiently make a query like the following:
Retrieve the product names of all products that were sold more than X times between date Y and date Z.
(X is the quantity sold not the number of transactions) | ```
SELECT p.[name]
FROM products p
WHERE p.product_id in (SELECT s.product_id
FROM productsales s
WHERE s.[date] between @dateStart and @dateEnd
GROUP BY s.product_id
HAVING Sum(s.quantity) > @X )
``` | The above query is not entirely correct ...
```
SELECT Name FROM Products
WHERE ProductId IN
( SELECT ProductId
FROM ProductSales
WHERE ProductSales.Date BETWEEN Y AND Z
GROUP BY ProductId
HAVING SUM(ProductSales.Qty) > x
)
``` | SQL products/productsales | [
"",
"sql",
"inner-join",
""
] |
I have to ensure the security of a asp.net website at work. They asked me to do a role based security with the active directory of my work so I could do a sitemap and give the right access at the right person.
Which class of the framework should I use? make generic identity? | It's already built into AD authentication. If you are authenticating against the AD, either via NTLM logins or an AD connected forms authentication setup then the thread identity will contain the groups the user belongs to, and the role based parts of the sitemap control will work.
Specifically you use the *WindowsTokenRoleProvider*. This is a one way role manager (you can't add people to groups - you have to use the AD tools for that. The use the sitemap's [built in](http://msdn.microsoft.com/en-us/library/ms178428.aspx) support for trimming site maps according to role. | Yes, you can use a RoleManager. Have a look at <http://msdn.microsoft.com/en-us/library/ms998314.aspx> | Role security with active directory | [
"",
"c#",
".net",
"asp.net",
"security",
""
] |
I want to make a [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) program that can be run as a CLI or GUI application depending on what flags are passed into it. Can this be done?
I have found these related questions, but they don't exactly cover my situation:
* [How to write to the console in a GUI application](https://stackoverflow.com/questions/192294/how-to-write-to-the-console-in-a-gui-application)
* [How do I get console output in C++ with a Windows program?](https://stackoverflow.com/questions/191842/how-do-i-get-console-output-in-c-with-a-windows-program) | [Jdigital's answer](https://stackoverflow.com/questions/493536/can-one-executable-be-both-a-console-and-gui-app/493568#493568) points to [Raymond Chen's blog](https://devblogs.microsoft.com/oldnewthing/20090101-00/?p=19643), which explains why you can't have an application that's both a console program and a non-console`*` program: The OS needs to know *before the program starts running* which subsystem to use. Once the program has started running, it's too late to go back and request the other mode.
[Cade's answer](https://stackoverflow.com/questions/493536/can-one-executable-be-both-a-console-and-gui-app/493556#493556) points to [an article about running a .Net WinForms application with a console](http://www.csharp411.com/console-output-from-winforms-application/). It uses the technique of calling [`AttachConsole`](http://msdn2.microsoft.com/en-us/library/ms681952.aspx) after the program starts running. This has the effect of allowing the program to write back to the console window of the command prompt that started the program. But the comments in that article point out what I consider to be a fatal flaw: *The child process doesn't really control the console.* The console continues accepting input on behalf of the parent process, and the parent process is not aware that it should wait for the child to finish running before using the console for other things.
Chen's article points to [an article by Junfeng Zhang that explains a couple of other techniques](http://blogs.msdn.com/junfeng/archive/2004/02/06/68531.aspx).
The first is what *devenv* uses. It works by actually having two programs. One is *devenv.exe*, which is the main GUI program, and the other is *devenv.com*, which handles console-mode tasks, but if it's used in a non-console-like manner, it forwards its tasks to *devenv.exe* and exits. The technique relies on the Win32 rule that *com* files get chosen ahead of *exe* files when you type a command without the file extension.
There's a simpler variation on this that the Windows Script Host does. It provides two completely separate binaries, *wscript.exe* and *cscript.exe*. Likewise, Java provides *java.exe* for console programs and *javaw.exe* for non-console programs.
Junfeng's second technique is what *ildasm* uses. He quotes the process that *ildasm*'s author went through when making it run in both modes. Ultimately, here's what it does:
1. The program is marked as a console-mode binary, so it always starts out with a console. This allows input and output redirection to work as normal.
2. If the program has no console-mode command-line parameters, it re-launches itself.
It's not enough to simply call `FreeConsole` to make the first instance cease to be a console program. That's because the process that started the program, *cmd.exe*, "knows" that it started a console-mode program and is waiting for the program to stop running. Calling `FreeConsole` would make *ildasm* stop using the console, but it wouldn't make the parent process *start* using the console.
So the first instance restarts itself (with an extra command-line parameter, I suppose). When you call `CreateProcess`, there are two different flags to try, [`DETACHED_PROCESS` and `CREATE_NEW_CONSOLE`](http://msdn.microsoft.com/en-us/library/ms684863.aspx), either of which will ensure that the second instance will not be attached to the parent console. After that, the first instance can terminate and allow the command prompt to resume processing commands.
The side effect of this technique is that when you start the program from a GUI interface, there will still be a console. It will flash on the screen momentarily and then disappear.
The part in Junfeng's article about using *editbin* to change the program's console-mode flag is a red herring, I think. Your compiler or development environment should provide a setting or option to control which kind of binary it creates. There should be no need to modify anything afterward.
The bottom line, then, is that **you can either have two binaries, or you can have a momentary flicker of a console window**. Once you decide which is the lesser evil, you have your choice of implementations.
`*` I say *non-console* instead of *GUI* because otherwise it's a false dichotomy. Just because a program doesn't have a console doesn't mean it has a GUI. A service application is a prime example. Also, a program can have a console *and* windows. | Check out Raymond's blog on this topic:
<https://devblogs.microsoft.com/oldnewthing/20090101-00/?p=19643>
His first sentence: "You can't, but you can try to fake it." | Can one executable be both a console and GUI application? | [
"",
"c#",
"user-interface",
"command-line-interface",
""
] |
I've got a question about testing methods working on strings. Everytime, I write a new test on a method that has a string as a parameter.
Now, some issues come up:
* How to include a test string with \n, \r, \t, umlauts etc?
* How to set the encoding?
* Should I use external files that are opened by a FileInputStream? (too much overhead, imho)
So... what are your approaches to solve this? | > How to include a test string with \n, \r, \t, umlauts etc?
Um... just type it the way you want? You can use \n, \r and \t, umlauts stc. in Java String literals; if you're worried about the encoding of the source code file, you can use [Unicode escape sequences](http://en.wikibooks.org/wiki/Java_Programming/Syntax/Unicode_Escape_Sequences), and you can produce them using the native2ascii tool that comes with the JDK.
> How to set the encoding?
Once you have a Java String, it's too late to worry about encodings - they use UTF-16, and any encoding problems occur when translating between Strings and byte arrays (unlike C, Java keeps these concepts clearly separate)
**Edit:**
If your Strings are too big to be comfortably used in source code or you're really worried about the treatment of line breaks and white space, then keeping each String in a separate file is probably best; in that case, the encoding must be specified when reading the file (In the constructor of `InputStreamReader`) | * If you have a lot of them, keep test strings in separate class with string consts
* Try not to keep the files on disk unless you must. I agree with your claim - this brings too much overhead (not to mention what happens if you start getting I/O errors)
* Make sure you test strings with different line breaks (`\n`, `\r\n`, `\r\n\r`) for different OSs | How to handle large strings in unit tests? | [
"",
"java",
"unit-testing",
"junit",
""
] |
What are the best tools/libraries (in any language) for working with 2D constructive area geometry?
That is, a library working with more or less arbitrary two dimensional shapes and supplying union, intersection, difference and XOR.
My baseline is the [java.awt.geom.Area](http://java.sun.com/javase/6/docs/api/java/awt/geom/Area.html) class, and that's serviceable if slow. What's out there that's better? My particular interests are Java, ActionScript/Flex, and C libraries, but I'm open to any comers. | Two options come in mind
1. [Cairo Graphics](http://www.cairographics.org/) for C
2. [Antigrain](http://www.antigrain.com/) for C++
I propose Cairo.
It is
* Mature
* Tested (used internally in GTK+ and Mozilla)
* supported (great community mailing list, irc, web e.t.c)
* Open Source
Cairo has already the operators you mention (union, intersection, difference e.t.c)
and using paths you can draw any shape you can imagine. | The [Computational Geometry Algorithms Library](http://www.cgal.org/) is quite extensive. It had a commercial and an open source license last time I checked. | Best Tools for 2D Constructive Area Geometry | [
"",
"java",
"c",
"apache-flex",
"geometry",
""
] |
How do I map a CHAR(1) to a boolean using Hibernate for Java? | The `true_false` or `yes_no` types will do this for you. | CharBooleanType is probably what you are looking for <http://www.hibernate.org/hib_docs/v3/api/org/hibernate/type/class-use/CharBooleanType.html>
edit: dtsazza's answer is probably more useful if you just want to get going and use characters y/n or t/f. If those don't match your usage you can implement your own type using CharBooleanType. | How do I map a CHAR(1) to a boolean using Hibernate for Java? | [
"",
"java",
"hibernate",
""
] |
I have a user control in a master page and the same user control directly in the aspx. The user control in the master page works fine, but when I try the user control that is embedded directly in the aspx page, it doesn't work. The user control is 2 textboxes with a login button. What it looks like it is trying to do is when I enter my username and password for the embedded user control, it sees that the user controls textboxes that are in the master page are blank and it complains. Is there a way to handle this properly?
The event handler for the user control that is embedded directly in the page is not being called.
Here is the button for the login control:
```
<asp:ImageButton ID="ibtnLoginButton" runat="server" CommandName="Login"
ImageUrl="~/images/sign-in.png"
ValidationGroup="ctl00$Login1" OnClick="LoginButton_OnClick"
meta:resourcekey="LoginButtonResource1" />
``` | It is hard to tell exactly what the problem is without more information.
From what you are saying, it could be client-side validation that kicks in. If this is the case, you could set ValidationGroup on the controls to the ID of the UserControl. Then the controls on the same instance of the UserControl will have the same validation group and thus be validated as a unit. | It sounds like your controls are sharing a ValidationGroup - can you post some code so we can see? | Using two user controls on the same page? | [
"",
"c#",
"asp.net",
"user-controls",
""
] |
I am hopeless with regex (c#) so I would appreciate some help:
Basicaly I need to parse a text and I need to find the following information inside the text:
Sample text:
**KeywordB:\*\*\*TextToFind\* the rest is not relevant but \*\*KeywordB:** *Text ToFindB* and then some more text.
I need to find the word(s) after a certain keyword which may end with a “:”.
**[UPDATE]**
Thanks Andrew and Alan: Sorry for reopening the question but there is quite an important thing missing in that regex. As I wrote in my last comment, Is it possible to have a variable (how many words to look for, depending on the keyword) as part of the regex?
Or: I could have a different regex for each keyword (will only be a hand full). But still don't know how to have the "words to look for" constant inside the regex | Let me know if I should delete the old post, but perhaps someone wants to read it.
The way to do a "words to look for" inside the regex is like this:
```
regex = @"(Key1|Key2|Key3|LastName|FirstName|Etc):"
```
What you are doing probably isn't worth the effort in a regex, though it can *probably* be done the way you want (still not 100% clear on requirements, though). It involves looking ahead to the next match, and stopping at that point.
Here is a re-write as a regex + regular functional code that should do the trick. It doesn't care about spaces, so if you ask for "Key2" like below, it will separate it from the value.
```
string[] keys = {"Key1", "Key2", "Key3"};
string source = "Key1:Value1Key2: ValueAnd A: To Test Key3: Something";
FindKeys(keys, source);
private void FindKeys(IEnumerable<string> keywords, string source) {
var found = new Dictionary<string, string>(10);
var keys = string.Join("|", keywords.ToArray());
var matches = Regex.Matches(source, @"(?<key>" + keys + "):",
RegexOptions.IgnoreCase);
foreach (Match m in matches) {
var key = m.Groups["key"].ToString();
var start = m.Index + m.Length;
var nx = m.NextMatch();
var end = (nx.Success ? nx.Index : source.Length);
found.Add(key, source.Substring(start, end - start));
}
foreach (var n in found) {
Console.WriteLine("Key={0}, Value={1}", n.Key, n.Value);
}
}
```
And the output from this is:
```
Key=Key1, Value=Value1
Key=Key2, Value= ValueAnd A: To Test
Key=Key3, Value= Something
``` | The basic regex is this:
```
var pattern = @"KeywordB:\s*(\w*)";
\s* = any number of spaces
\w* = 0 or more word characters (non-space, basically)
() = make a group, so you can extract the part that matched
var pattern = @"KeywordB:\s*(\w*)";
var test = @"KeywordB: TextToFind";
var match = Regex.Match(test, pattern);
if (match.Success) {
Console.Write("Value found = {0}", match.Groups[1]);
}
```
If you have more than one of these on a line, you can use this:
```
var test = @"KeywordB: TextToFind KeyWordF: MoreText";
var matches = Regex.Matches(test, @"(?:\s*(?<key>\w*):\s?(?<value>\w*))");
foreach (Match f in matches ) {
Console.WriteLine("Keyword '{0}' = '{1}'", f.Groups["key"], f.Groups["value"]);
}
```
Also, check out the regex designer here: [http://www.radsoftware.com.au/](http://www.radsoftware.com.au/regexdesigner/). It is free, and I use it constantly. It works great to prototype expressions. You need to rearrange the UI for basic work, but after that it's easy.
*(fyi) The "@" before strings means that \ no longer means something special, so you can type @"c:\fun.txt" instead of "c:\fun.txt"* | How can I find a string after a specific string/character using regex | [
"",
"c#",
"regex",
""
] |
In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32? | \_RPTn works great, though not quite as convenient. [Here is some code](http://www.codeguru.com/cpp/v-s/debug/article.php/c4405) that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.
Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. *Thanks to Thomas Rizos for the original*:
```
// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873
#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#ifdef _DEBUG
#define TRACEMAXSTRING 1024
char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
va_list args;
va_start(args,format);
int nBuf;
nBuf = _vsnprintf(szBuffer,
TRACEMAXSTRING,
format,
args);
va_end(args);
_RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
&strrchr(__FILE__,'\\')[1],__LINE__); \
_RPT0(_CRT_WARN,szBuffer); \
TRACE
#else
// Remove for release mode
#define TRACE ((void)0)
#define TRACEF ((void)0)
#endif
#endif // __TRACE_H__850CE873
``` | From the msdn docs, [Macros for Reporting](http://msdn.microsoft.com/en-us/library/yt0c3wdh(VS.80).aspx):
> You can use the \_RPTn, and \_RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when \_DEBUG is not defined, so there is no need to enclose them in #ifdefs. | Is there a TRACE statement for basic win32 C++? | [
"",
"c++",
"debugging",
"winapi",
"visual-c++-6",
""
] |
I want to use the jQuery accordion tool for a form i'm building so I used some sample code from the jquery website but it doesn't work at all!
The javascript does nothing at all so you just get the html rendered. I am using version 1.3.1 of jquery with version 1.6rc6 of jquery-ui.
```
<head runat="server">
<script src="/scripts/jquery-1.3.1.js" type="text/javascript"></script>
<script src="/scripts/jquery-ui-personalized-1.6rc6" type="text/javascript"></script>
<title>JQuery Test</title>
</head>
<body>
<div class="demo">
<div id="accordion">
<div>
<h3><a href="#">Section 1</a></h3>
<div>
<p>
Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
</p>
</div>
</div>
<div>
<h3><a href="#">Section 2</a></h3>
<div>
<p>
Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
suscipit faucibus urna.
</p>
</div>
</div>
<div>
<h3><a href="#">Section 3</a></h3>
<div>
<p>
Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
</p>
<ul>
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
</ul>
</div>
</div>
<div>
<h3><a href="#">Section 4</a></h3>
<div>
<p>
Cras dictum. Pellentesque habitant morbi tristique senectus et netus
et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
mauris vel est.
</p>
<p>
Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
inceptos himenaeos.
</p>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(
function() {
$('#accordion').Accordion(
{
header: "h3"
}
);
</script>
</body>
</html>
```
I've tried everything i can think of and trawled the net and still can't get this simple demo to work, can anyone point me in the right direction?
It doesn't matter what browser I use but firebug says $("#accordion").accordion is not a function
Thanks | The accordion function is all lowercase, you have also one missing parenthesis and one curly brace:
```
$(document).ready(
function() {
$('#accordion').accordion(
{
header: "h3"
});
}
);
```
See your script running [here](http://jsbin.com/ekeja) and if you want to play with your code go [here](http://jsbin.com/ekeja/edit). | are you sure the js reference is correct and loaded?
have you tried using firebug's js debugger in order to step into the jquery code to verify this?
edit: shouldnt the function call to Accordion be lowercase? | JQuery accordion not hiding sections | [
"",
"javascript",
"jquery",
""
] |
I think the basic principle of a PHP templating system is string replacing, right?
So can I just use a string to hold my html template code like
```
$str_template = "<html><head><title>{the_title}</title><body>{the_content}</body></html>"
```
and in the following code simply do a str\_replace to push the data into my template variable like
```
str_replace( $str_template, '{the_title}', $some_runtime_generated_title );
str_replace( $str_template, '{the_content}', $some_runtime_generated_content );
```
then at last
```
echo $str_template;
```
Will this hopefully make the whole variable passing process a bit faster? I know this could be a weird question but has anybody tried it? | That is generally the basic idea for a templating system. Real templating systems have many more capabilities, but at the core this is what they do.
You ask whether this will "make the whole variable passing process a bit faster". Faster than what? Are you running into performance problems with something you're doing right now? | Yes, that is the basic idea behind a templating system. You could further abstract it, let an other method add the brackets for example.
You could also use arrays with str\_replace and thus do many more replaces with one function call like this
```
str_replace(array('{the_title}', '{the_content}'), array($title, $content), $str_template);
```
The system I work with is [Spoon Library](http://docs.spoon-library.be/), their templating system is pretty rock solid, including compiled templates, which are a huge performance gain. | PHP templating with str_replace? | [
"",
"php",
"templates",
""
] |
I noticed today that auto-boxing can sometimes cause ambiguity in method overload resolution. The simplest example appears to be this:
```
public class Test {
static void f(Object a, boolean b) {}
static void f(Object a, Object b) {}
static void m(int a, boolean b) { f(a,b); }
}
```
When compiled, it causes the following error:
```
Test.java:5: reference to f is ambiguous, both method
f(java.lang.Object,boolean) in Test and method
f(java.lang.Object,java.lang.Object) in Test match
static void m(int a, boolean b) { f(a, b); }
^
```
The fix to this error is trivial: just use explicit auto-boxing:
```
static void m(int a, boolean b) { f((Object)a, b); }
```
Which correctly calls the first overload as expected.
So why did the overload resolution fail? Why didn't the compiler auto-box the first argument, and accept the second argument normally? Why did I have to request auto-boxing explicitly? | When you cast the first argument to Object yourself, the compiler will match the method without using autoboxing (JLS3 15.12.2):
> The first phase (§15.12.2.2) performs
> overload resolution without permitting
> boxing or unboxing conversion, or the
> use of variable arity method
> invocation. If no applicable method is
> found during this phase then
> processing continues to the second
> phase.
If you don't cast it explicitly, it will go to the second phase of trying to find a matching method, allowing autoboxing, and then it is indeed ambiguous, because your second argument can be matched by boolean or Object.
> The second phase (§15.12.2.3) performs
> overload resolution while allowing
> boxing and unboxing, but still
> precludes the use of variable arity
> method invocation.
Why, in the second phase, doesn't the compiler choose the second method because no autoboxing of the boolean argument is necessary? Because after it has found the two matching methods, only subtype conversion is used to determine the most specific method of the two, regardless of any boxing or unboxing that took place to match them in the first place (§15.12.2.5).
Also: the compiler can't always choose the most specific method based on the number of auto(un)boxing needed. It can still result in ambiguous cases. For example, this is still ambiguous:
```
public class Test {
static void f(Object a, boolean b) {}
static void f(int a, Object b) {}
static void m(int a, boolean b) { f(a, b); } // ambiguous
}
```
Remember that the algorithm for choosing a matching method (compile-time step 2) is fixed and described in the JLS. Once in phase 2 there is no selective autoboxing or unboxing. The compiler will locate *all* the methods that are accessible (both methods in these cases) and applicable (again the two methods), and only then chooses the most specific one without looking at boxing/unboxing, which is ambiguous here. | The compiler *did* auto-box the first argument. Once that was done, it's the second argument that's ambiguous, as it could be seen as either boolean or Object.
[This page](http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html) explains the rules for autoboxing and selecting which method to invoke. The compiler first tries to select a method *without using any autoboxing at all*, because boxing and unboxing carry performance penalties. If no method can be selected without resorting to boxing, as in this case, then boxing is on the table for *all* arguments to that method. | Why does autoboxing make some calls ambiguous in Java? | [
"",
"java",
"compiler-construction",
"overloading",
"autoboxing",
""
] |
I have to replace the content of this xml string through java
```
<My:tag>value_1 22
value_2 54
value_3 11</My:tag>
```
so, this string has been taken from an xml and when I acquire it I have this result:
```
<My:tag>value_1 22
value_2 54
value_3 11</My:tag>
```
If I try to replace the content by this way:
```
String regex = "(<My:tag>)(.*)(</My:tag>)";
String new_string = old_string.replaceAll(regex,"<My:tag> new_stuff </My:tag>");
```
I get no result. I think because of the `
` symbol
but if I try to replace the string without the `
` symbol, everything goes fine.
Suggestions?
Thanks | I'm not 100% sure how the java regex-engine works, but I can't possibly imagine that an entity would cause your problems. You should first try to simply remove your brackets, since you're replacing the entire expression, and not extracting anything.
What might be causing it though is if your entity is actually translated to a new-line, it might be the case that your regex won't catch it unless you're explicitly doing a multiline match. You could also try doing
```
[.\n]*
```
instead of your
```
.*
```
This might be a bid greedy though, and the backtracking to much for the matcher to handle. Unfortunately, I don't have any java stuff installed on this machine, so I can't really try it and test it. One other possibility would be to actively look for the next opening angle bracket, like so:
```
[^<]*
```
**EDIT:**
As you suggested, i tried your link and the following worked perfectly:
Expression:
```
<My:tag>[^<]*</My:tag>
```
Replacement:
```
<My:tag> new_stuff </My:tag>
```
Test string:
```
<My:tag>value_1 22
value_2 54
value_3 11</My:tag>
``` | I can't see why the `
` itself would cause any issue - not unless it's getting converted to an actual newline at some point.
If this is the case, you need to enable DOTALL mode, so that the . matches newline also (which it doesn't by default).
To enable DOTALL, simply start the expression with `(?s)`
(if you created a Pattern object, you could also pass the flag in to that.)
Anyway, try this:
```
String regex = "(?s)(?<=<(My:tag)>).*?(?=</\1>)";
String new_string = old_string.replaceAll(regex,"new_stuff");
```
You can also enable it for a specific part of a regex with `(?s:`*regex-segment*`)` for example:
```
String regex = "(?<=<(My:tag)>)(?s:.*?)(?=</\1>)";
``` | replacing regex in java string, which contains `
` symbol | [
"",
"java",
"regex",
"replace",
""
] |
Here's the scenario: I have a multi threaded java web application which is running inside a servlet container.
The application is deployed multiple times inside the servlet container. There are multiple servlet containers
running on different servers.
Perhaps this graph makes it clear:
```
server1
+- servlet container
+- application1
| +- thread1
| +- thread2
+- application2
+- thread1
+- thread2
server2
+- servlet container
+- application1
| +- thread1
| +- thread2
+- application2
+- thread1
+- thread2
```
There is a file inside a network shared directory which all those threads can access. And they do access the file frequently.
Most of the time the file is only read by those threads. But sometimes it is written.
### I need a fail safe solution to synchronize all those threads so data consistency is guaranteed.
---
**Solutions which do not work (properly)**:
1. *Using java.nio.channels.FileLock*
I am able to synchronize threads from different servers using the FileLock class. But this does not work for threads
inside the same process (servlet container) since file locks are available process wide.
2. *Using a separate file for synchronization*
I could create a separate file which indicates that a process is reading from or wrinting to the file. This solution
works for all threads but has several drawbacks:
* Performance. Creating, deleting and checking files are rather slow operations. The low weight implementations with one synchronization file will prevent parallel reading of the file.
* The synchronization file will remain after a JVM crash making a manual clean up necessary.
* We have had already strange problems deleting files on network file systems.
3. *Using messaging*
We could implement a messaging system which the threads would use to coordinate the file access. But this seems too complex for this problem. And again: performance will be poor.
Any thoughts? | If you only need to write the file rarely, how about writing the file under a temporary name and then using rename to make it "visible" to the readers?
This only works reliably with Unix file systems, though. On Windows, you will need to handle the case that some process has the file open (for reading). In this case, the rename will fail. Just try again until the rename succeeds.
I suggest to test this thoroughly because you might run into congestion: There are so many read requests that the writer task can't replace the file for a long time.
If that is the case, make the readers check for the temporary file and wait a few moments with the next read until the file vanishes. | You've enumerated the possible solutions except the obvious one: *remove the dependency on that file*
Is there another way for the threads to obtain that data instead of reading it from a file? How about setting up some kind of process who is responsible for coordinating access to that information instead of having all the threads read the file. | How to lock a file on different application levels? | [
"",
"java",
"multithreading",
"file",
"synchronization",
"locking",
""
] |
I have recently been working with someone on a project that is very ajax intense. All calls are made to web services using ajax and the data logic is handled on the client side. The server side code just acts as the [data access layer](http://en.wikipedia.org/wiki/Data_access_layer) and does little else. How much javascript is too much? | It really depends on your needs and the user's expectations. My only suggestion is to think of the places you are doing AJAX when the user instead **really** expects to navigate a new page. Those are the cases where you are doing "too much".
Remember, the user spends 99% percent of his time using other sites, not yours. Make sure your site does what he/she expects from the rest of the web as well as from using computers in general.
By the way, usability testing can be used to figure out "what the user really expects" in any area. Your judgments as a designer are likely completely different than typical users'; see also [Why You Only Need to Test with 5 Users](http://www.useit.com/alertbox/20000319.html). | Javascript may be too much when it reveals too much to the client, so I would look from the security perspective. From the performance perspective in general using Javascript is better. | How much javascript is too much | [
"",
"javascript",
"ajax",
""
] |
i use the command line in windows to compile and then execute my java programs. i've gone to <http://java.sun.com/docs/books/tutorial/uiswing/start/compile.html> and tried compiling the HelloWorldSwing.java class. it worked, but when i try "java HelloWorldSwing" it gives me a bunch of erros and says something along the lines of Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldSwing (wrong name: start/HelloWorldSwing)
i try running with java start/HelloWorldSwing and it says noClassDefFoundError. i get no errors with javac either. here's the code from the tutorial:
```
import javax.swing.*;
public class HelloWorldSwing {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
```
EDIT: used javaw
window pops up
"a java exception has occurred"
another window
"error: could not find the main class.
error: a jni error has occurred, please check your installation and try again."
never had any problems running any java programs, am i missing something? is there a way to know what it is?
i'm also running the command in the same path where the .java and .class are.
there is no folder start in the path where i compiled the program.
EDIT2
I tried both start/HelloWorldSwing and HelloWorldSwing with java.
I don't get any errors with javac also. I get 2 pop up windows with the messages I've typed previously when I use javaw and java gives me the NoClassDefFoundException, then talks about the ClassLoaders and whatnot.
EDIT3
I got it to work by removing the "package start;" line. what would i have to do to make it work with that?
javaw also works now that I removed the package line. | Yep. That page has a slight bug:
The class uses a package, but in the run instructions the package is not used
You can do two things:
a) Drop the package name (delete the line `pacakge start;`) and run as indicated
Or
b) Leave the `package start;` line in the code and append the `-d` option to `javac` and use the full class name.
I hope this helps. | Where are you invoking the `java` command from? From your description, HelloWorldSwing.class is in the folder "start", but is not in a package. This is likely the source of the error. Try:
```
cd start
java HelloWorldSwing
```
EDIT: The code from the tutorial does have a "`package start;`" declaration in it. Did you remove it? If not, put HelloWorldSwing into the folder "start" and run
```
java start.HelloWorldSwing
```
from the current folder.
See also the [package tutorial](http://java.sun.com/docs/books/tutorial/java/package/packages.html). | can't run swing from the command line | [
"",
"java",
"swing",
""
] |
I'd like to do something like this to tick a `checkbox` using **jQuery**:
```
$(".myCheckBox").checked(true);
```
or
```
$(".myCheckBox").selected(true);
```
Does such a thing exist? | ## Modern jQuery
Use [`.prop()`](https://api.jquery.com/prop):
```
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
```
## DOM API
If you're working with just one element, you can always just access the underlying [`HTMLInputElement`](https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement) and modify its [`.checked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#Properties_checkbox_radio) property:
```
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
```
The benefit to using the `.prop()` and `.attr()` methods instead of this is that they will operate on all matched elements.
## jQuery 1.5.x and below
The `.prop()` method is not available, so you need to use [`.attr()`](https://api.jquery.com/attr).
```
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
```
Note that this is [the approach used by jQuery's unit tests prior to version 1.6](https://github.com/jquery/jquery/blob/1.5.2/test/unit/attributes.js#L157) and is preferable to using `$('.myCheckbox').removeAttr('checked');` since the latter will, if the box was initially checked, change the behaviour of a call to [`.reset()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.reset) on any form that contains it – a subtle but probably unwelcome behaviour change.
For more context, some incomplete discussion of the changes to the handling of the `checked` attribute/property in the transition from 1.5.x to 1.6 can be found in the [version 1.6 release notes](https://blog.jquery.com/2011/05/03/jquery-16-released/) and the **Attributes vs. Properties** section of the [`.prop()` documentation](https://api.jquery.com/prop). | Use:
```
$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);
```
And if you want to check if a checkbox is checked or not:
```
$('.myCheckbox').is(':checked');
``` | Setting "checked" for a checkbox with jQuery | [
"",
"javascript",
"jquery",
"checkbox",
"selected",
"checked",
""
] |
I have a WPF form and I am working with databinding. I get the events raised from INotifyPropertyChanged, but I want to see how to get a list of what items are listening, which i fire up the connected handler.
How can I do this? | <http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx> | What do you mean with the Items that are listening ?
Do you want to know which controls are databound to your property , or do you want to have a list of eventhandlers that are wired to the PropertyChanged event ?
The latter can be done by calling GetInvocationList on the event. | Finding out who is listening for PropertyChangedEventHandler in c# | [
"",
"c#",
"wpf",
"data-binding",
"inotifypropertychanged",
""
] |
Can I programatically change the quality of a PDF?
I have a client that is a newspaper, and when they submit the PDF form of the paper to their site they are submitting the same copy they send to the printer which can range from 30-50Mb. I can manually lower the quality (still plenty high for the web) and it will be 3-5Mb so this will help my hosting substantially. | That seems like something that would require nothing short of the Adobe PDF SDK / libraries. I have worked with them quite bit, but I have never attempted to change the resolution of an existing PDF. The libraries are pricey so it's likely that is not an option for you.
I want to say that Perl's PDF::API2 has an optimize script bundled with it, but I have never used that functionality. It may be worth a look. The module itself is pretty thorough. Although, a PDF that large not be that fastest to process with it. | You should check [TCPDF](http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=tcpdf) library or [php documentation](http://ar.php.net/pdf).
I never worked with pdfs in php, but I think you can do that you need with TCPDF easily. If your pdf is composed by images, check [this example](http://www.tecnick.com/pagefiles/tcpdf/example_009.phps), maybe help you.
Regards | Programatically changing PDF quality in PHP | [
"",
"php",
"pdf",
""
] |
It's been at least 5 years since I worked with Java, and back then, any time you wanted to allocate an object that needed cleaning up (e.g. sockets, DB handles), you had to remember to add a `finally` block and call the cleanup method in there.
By contrast, in C++ (or other languages where object lifetimes are deterministic, e.g. Perl), the class implementor would define a destructor function that performs the cleanup whenever an object of that class goes out of scope. The advantage of this approach is that the user of the object can't forget to clean it up -- the destructor gets called automatically, even if an exception is thrown. This approach goes by the fairly awful name of RAII -- "Resource Acquisition Is Initialisation".
It's been my experience that doing things "the RAII way" has saved me a lot of mental overhead in terms of not having to worry about whether and when resource deallocations occur. We are considering using Java for a medium-sized project, and I'm wondering if some sort of deterministic destruction is among the many new features added to the language since I last looked at it. (I'm hopeful as my complaint that "Java has no RAII" was rebuked [on this thread](https://stackoverflow.com/questions/457884/what-are-the-things-java-got-wrong#475089), but so far I haven't been able to find any details by googling.)
So if someone could point me to some introductory material on how to go about this in Java that would be great! | EDIT: The answer below was written in early 2009, when Java 7 was very much still in flux.
While Java still doesn't provide guarantees around finalization timing, it *did* gain a feature like C#'s `using` statement: the [try-with-resources statement](http://download.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html).
---
No, Java hasn't changed at all in that respect. You still need to use try/finally.
There's been discussion of adding the equivalent of C#'s "using" statement (which is syntactic sugar over try/finally) to Java, but I don't think that's going to be part of Java 7 any more. (Most of the language improvements seem to have been dropped.)
It's worth understanding that there are reasons why deterministic destruction hasn't been implemented in Java and .NET in the form of a reference-counted garbage collector, by the way - that a) impacts performance and b) fails with circular references. Brian Harry wrote a [detailed email](http://blogs.msdn.com/brada/articles/371015.aspx) about this - it's about .NET and it's rather old, but it's well worth a close read. | There is a pattern that helps here. It's not as nice as destructor based RAII but it does mean that the resource clean-up can be moved to the library (so you can't forget to call it).
It's called [Execute Around, and has been discussed here before](https://stackoverflow.com/questions/341971/what-is-the-execute-around-idiom).
Interestingly I see Jon Skeet chimed in on that thread, but he didn't mention it here - shame on you Jon - missed an opportunity for some rep points there!
BTW, while I'm glad Brian Harry (see Jon's comment, again) went to the lengths of writing the email that he did - and it obviously did reflect a lot of thought that went into the process - and I'm glad we did get "using" out of it in C# - I don't agree with all his conclusions. In particular, I don't see why, if we can have using, we can't have a way to mark a type as behaving that way without "using". Of course it constrains the usage - but so does "using" - and most of the time it's exactly what you want. The trouble with "using" is that the client code still has to remember to use it. With C++ style RAII it's a property of the type. An arguably bigger problem with "using", or more accurately with the Dispose idiom, is that it's a lot more complicated and error prone than most people realise to get right - mostly because of the potential for objects to be brought back from the dead. | Does Java support RAII/deterministic destruction? | [
"",
"java",
"raii",
""
] |
They both do the same thing. Is one way better? Obviously if I write the code I'll know what I did, but how about someone else reading it?
```
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Open", "ServiceCall");
```
OR
```
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Open", "ServiceCall");
}
``` | ```
return String.IsNullOrEmpty(returnUrl) ?
RedirectToAction("Open", "ServiceCall") :
Redirect(returnUrl);
```
I prefer that.
Or the alternative:
```
return String.IsNullOrEmpty(returnUrl)
? RedirectToAction("Open", "ServiceCall")
: Redirect(returnUrl);
``` | I believe it's better to remove the not (negation) and get the positive assertion first:
```
if (String.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Open", "ServiceCall");
}
else
{
return Redirect(returnUrl);
}
```
-or-
```
// Andrew Rollings solution
return String.IsNullOrEmpty(returnUrl) ?
RedirectToAction("Open", "ServiceCall") :
Redirect(returnUrl);
``` | What is the cleanest way to write this if..then logic? | [
"",
"c#",
"coding-style",
""
] |
Whatever I try to compile in Cygwin I get the following output:
```
checking for mingw32 environment... no
checking for EMX OS/2 environment... no
checking how to run the C preprocessor... gcc -E
checking for gcc... gcc
checking whether the C compiler (gcc ) works... no
configure: error: installation or configuration problem: C compiler cannot creat
e executables.
```
The last few lines of the logfile look like this:
```
configure:2810: checking for EMX OS/2 environment
configure:2822: gcc -c conftest.c 1>&5
configure: In function `main':
configure:2818: error: `__EMX__' undeclared (first use in this function)
configure:2818: error: (Each undeclared identifier is reported only once
configure:2818: error: for each function it appears in.)
configure: failed program was:
#line 2815 "configure"
#include "confdefs.h"
int main() {
return __EMX__;
; return 0; }
configure:2838: checking how to run the C preprocessor
configure:2859: gcc -E conftest.c >/dev/null 2>conftest.out
configure:2943: checking for gcc
configure:3056: checking whether the C compiler (gcc ) works
configure:3072: gcc -o conftest conftest.c -llib 1>&5
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/bin/ld: cannot find
-llib
collect2: ld returned 1 exit status
configure: failed program was:
#line 3067 "configure"
#include "confdefs.h"
main(){return(0);}
```
This is a fresh Cygwin install with G++ and a bunch of other devtools added. Any idea what I need to do to get this thing working?
Update 0: Nick, your link to <http://www.geektimes.com/linux/troubleshooting/c-cant-create-executables.html> was tried already - unfortunately this instructions are for redhat and do not seem to apply to cygwin. | Your Configure is wrong.
Usually `autoreconf -f` helps. If not you need to check the failing rule and fix it. | The '-llib' seems a bit unusual to me, but I'm far from an expert. Just out of curiosity is autoconf installed? I had some problems similar to this until I installed autoconf. It seems like the configure script is incorrectly generating a '-llib' value but it's hard to say why based on just the snippets posted. | Dealing with "C compiler cannot create executables" in Cygwin | [
"",
"c++",
"gcc",
"compiler-construction",
"cygwin",
"g++",
""
] |
Please help us settle the controversy of *"Nearly" everything is an object* ([an answer to Stack Overflow question *As a novice, is there anything I should beware of before learning C#?*](https://stackoverflow.com/questions/436079/as-a-novice-is-there-anything-i-should-beware-of-before-learning-c#436092)). I thought that was the case as everything in Visual Studio at least appears as a struct. Please post a reference, so that it doesn't become "modern jackass" ([This American Life](http://en.wikipedia.org/wiki/This_American_Life)).
Note that this question refers to C#, not necessarily .NET, and how it handles the data under the hood (obviously it's all 1's and 0's).
Here are the comments to "everything is an object":
* Eh, no, it's not. – Binary Worrier
* I'd like an example... – scotty2012
* isn't everything derived from the
base type Object? – rizzle
* Most things are objects... – Omar
Kooheji
* Value types, ints, doubles, object
references (not the objects them
selves) etc aren't objects. They can
be "boxed" to look like objects (e.g.
i.ToString()) but really they're
primitive types. Change the entry to
"NEARLY everthing is an object" and
I'll remove the downvote – Binary
Worrier
* I appreciate the clarification. I
think the lowest level that you can
interact with, say an int, in C# is
as a struct, which isn't an object? -
<http://msdn.microsoft.com/en-us/library/ms173109.aspx>
– rizzle
* Doesn't Int32 inherit from ValueType
which inherits from Object? If so,
despite the behavior, an int is an
object. – Chris Farmer
* No, the boxed type for int inherits
from ValueType, which inherits from
Object. They're not objects in the
traditional sense because a) an int
isn't a reference to an int, IT IS
the int. b) ints aren't garbage
collected. If you declare an Int32,
then that int is 4 bytes on the
stack, end of story – Binary Worrier
Definition of object: "Object" as a inheritor of class System.Object vs. "object" as an instance of a type vs. "object" as a reference type." | The problem here is that this is really two questions - one question is about inheritance, in which case the answer is "nearly everything", and the other is about reference type vs value type/memory/boxing, which case the answer is "no".
**Inheritance:**
In C#, the following is true:
* All value types, including enums and nullable types, are derived from `System.Object`.
* All class, array, and delegate types are derived from `System.Object`.
* Interface types are not derived from `System.Object`. They are all convertible to `System.Object`, but interfaces only derive from other interface types, and `System.Object` is not an interface type.
* No pointer types derive from `System.Object`, nor are any of them directly convertible to `System.Object`.
* "Open" type parameter types are also not derived from `System.Object`. Type parameter types are not derived from anything; type arguments are constrained to be derived from the effective base class, but they themselves are not "derived" from anything.
From [the MSDN entry for System.Object](http://msdn.microsoft.com/en-us/library/system.object.aspx):
> Supports all classes in the .NET
> Framework class hierarchy and provides
> low-level services to derived classes.
> This is the ultimate base class of all
> classes in the .NET Framework; it is
> the root of the type hierarchy.
>
> Languages typically do not require a
> class to declare inheritance from
> Object because the inheritance is
> implicit.
>
> Because all classes in the .NET
> Framework are derived from Object,
> every method defined in the Object
> class is available in all objects in
> the system. Derived classes can and do
> override some of these methods.
So not every type in C# is derived from `System.Object`. And even for those types that are, you still need to note the difference between [reference types](http://msdn.microsoft.com/en-us/library/490f96s2.aspx) and [value types](http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx), as they are treated very differently.
**Boxing:**
While value types do *inherit* from `System.Object`, they are treated differently in memory from reference types, and the semantics of how they are passed through methods in your code are different as well. Indeed, a value type is not treated as an Object (a reference type), until you explicitly instruct your application to do so by boxing it as a reference type. See [more information about boxing in C# here](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx). | A little late to the party, but I came across this in a search result on SO and figured the link below would help future generations:
Eric Lippert [discusses this very thoroughly](http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx), with a much better (qualified) statement:
> The way to correct this myth is to simply replace "derives from" with "is convertible to", and to ignore pointer types: every non-pointer type in C# is convertible to object.
The gist of it, if you hate reading well-illustrated explanations from people that write programming languages, is that (pointers aside), things like Interface, or generic parameter type declarations ("T") are not objects, but are guaranteed to be treatable as objects at runtime, because they have a definite instance, that will be an Object. Other types (Type, Enum, Delegate, classes, etc.) are all Objects. Including value types, which can be boxed to object as other answers have discussed. | Is everything in .NET an object? | [
"",
"c#",
"object",
""
] |
Should my interface and concrete implementation of that interface be broken out into two separate files? | If you want other classes to implement that interface, it would probably be a good idea, if only for cleanliness. Anyone looking at your interface should not have to look at your implementation of it every time. | If there is only one implementation: why the interface?
If there is more than one implementation: where do you put the others? | Interfaces in Class Files | [
"",
"c#",
"interface",
""
] |
I'm trying to set up a C# application which uses TWAIN [example from code project](http://www.codeproject.com/KB/dotnet/twaindotnet.aspx)
This works fine except that I need to cast `Form` to `IMessageFilter` and
call `IMessageFilter.PreFilterMessage()` to catch TWAIN callbacks.
Also I need to start this filtering by calling
```
Application.AddMessageFilter();
```
Is there a way to do same thing in WPF Window? (To add message filter and catch TWAIN callbacks).
Another totally high level question:
Does anybody know about alternative C# TWAIN libraries\wrappers?
Thank you. | You could try it with the `ComponentDispatcher.ThreadFilterMessage` event.
As far as I understand, it serves the same purpose in *WPF* as `Application.AddMessageFilter()` in *WinForms*. | I've just wrapped up the code from Thomas Scheidegger's article ([CodeProject: .NET TWAIN image scanning](http://www.codeproject.com/KB/dotnet/twaindotnet.aspx)) into [github project](https://github.com/tmyroadctfig/twaindotnet)
I've cleaned up the API a bit and added WPF support, so check it out. :)
It has a simple WPF application that shows how the message filtering works with WPF. | C# TWAIN interaction | [
"",
"c#",
"wpf",
"imaging",
"image-scanner",
"twain",
""
] |
Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform?
```
while 1:
line = f.readline()
if line == "":
break
line = line[:-1]
print "\"" + line + "\""
``` | First of all, there is [universal newline support](https://www.python.org/dev/peps/pep-0278/)
Second: just use `line.strip()`. Use `line.rstrip('\r\n')`, if you want to preserve any whitespace at the beginning or end of the line.
Oh, and
```
print '"%s"' % line
```
or at least
```
print '"' + line + '"'
```
might look a bit nicer.
You can iterate over the lines in a file like this (this will not break on empty lines in the middle of the file like your code):
```
for line in f:
print '"' + line.strip('\r\n') + '"'
```
If your input file is short enough, you can use the fact that `str.splitlines` throws away the line endings by default:
```
with open('input.txt', 'rU') as f:
for line in f.read().splitlines():
print '"%s"' % line
``` | Try this instead:
```
line = line.rstrip('\r\n')
``` | python reading lines w/o \n? | [
"",
"python",
"file",
"newline",
""
] |
I received some text that is encoded, but I don't know what charset was used. Is there a way to determine the encoding of a text file using Python? [How can I detect the encoding/codepage of a text file](https://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file) deals with C#. | EDIT: chardet seems to be unmantained but most of the answer applies. Check <https://pypi.org/project/charset-normalizer/> for an alternative
Correctly detecting the encoding all times is **impossible**.
(From chardet FAQ:)
> However, some encodings are optimized
> for specific languages, and languages
> are not random. Some character
> sequences pop up all the time, while
> other sequences make no sense. A
> person fluent in English who opens a
> newspaper and finds “txzqJv 2!dasd0a
> QqdKjvz” will instantly recognize that
> that isn't English (even though it is
> composed entirely of English letters).
> By studying lots of “typical” text, a
> computer algorithm can simulate this
> kind of fluency and make an educated
> guess about a text's language.
There is the [chardet](http://pypi.python.org/pypi/chardet) library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.
You can also use [UnicodeDammit](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#unicode-dammit). It will try the following methods:
* An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.
* An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-\* encodings, EBCDIC, or ASCII.
* An encoding sniffed by the [chardet](http://pypi.python.org/pypi/chardet) library, if you have it installed.
* UTF-8
* Windows-1252 | Another option for working out the encoding is to use
[libmagic](http://linux.die.net/man/3/libmagic) (which is the code behind the
[file](http://linux.die.net/man/1/file) command). There are a profusion of
python bindings available.
The python bindings that live in the file source tree are available as the
[python-magic](http://packages.debian.org/search?keywords=python-magic&searchon=names&suite=all§ion=all) (or [python3-magic](http://packages.debian.org/search?keywords=python3-magic&searchon=names&suite=all§ion=all))
debian package. It can determine the encoding of a file by doing:
```
import magic
blob = open('unknown-file', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob) # "utf-8" "us-ascii" etc
```
There is an identically named, but incompatible, [python-magic](https://pypi.python.org/pypi/python-magic) pip package on pypi that also uses `libmagic`. It can also get the encoding, by doing:
```
import magic
blob = open('unknown-file', 'rb').read()
m = magic.Magic(mime_encoding=True)
encoding = m.from_buffer(blob)
``` | How to determine the encoding of text | [
"",
"python",
"encoding",
"text-files",
""
] |
I'm attempting to access member variables in a child class via the parent class without instantiation.
This is one of my attempts but `B::getStatic()` fails with `Access to undeclared static property`.
Is there another solution to this, possibly without static?
```
class A {
static public function getStatic() {
return self::$myStatic;
}
}
class B extends A {
public static $myStatic = 5;
}
class C extends A {
public static $myStatic = 6;
}
var_dump(B::$myStatic);
var_dump(B::getStatic());
var_dump(C::$myStatic);
var_dump(C::getStatic());
``` | The concept you're running into is called "Late Static Binding." Until PHP 5.3.0, there was no support for this.
If you're running 5.3.0 or higher, update the getStatic() method:
> static public function getStatic() {
>
> ```
> return static::$myStatic;
> ```
>
> } | The others are right, the way your code is it can't be done since the variable doesn't exist at compile time.
The way to do something like this is usually with an abstract class (available in PHP5 and up, it looks like).
Class A would be the abstract class, and would have a getStatic() function. Classes B and C would extend A and have definitions for the getStatic() function. This way, when you call getStatic() you will get the value the subclass defines since there is no definition in A.
The caveat to this approach is that you can't instantiate A since it's abstract. You would ALWAYS have to make a B or a C (or a subclass there-of).
You could also make a setter in A and have the subclasses use it to set the value (instead of an '='s). That would let you instantiate A and it could set the value if it ever needs to. You might be able to make the setter private so it can't be called directly, I don't know if subclasses can use private functions in PHP. | Accessing child variables from the super class without instanciation | [
"",
"php",
"oop",
"static",
""
] |
I've an old website, navigation in an frame at left, pages at right.
I want when an page is url'd directly the nav (left frame) shows also.
Until now I was an js working, but I don't know from when it are not working,
now returns this message:
*Forbidden
You don't have permission to access /master.html on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Apache/2.2.10 (Unix) mod\_ssl/2.2.10 OpenSSL/0.9.8i DAV/2 mod\_auth\_passthrough/2.1 mod\_bwlimited/1.4 FrontPage/5.0.2.2635 Server at www.cpis.es Port 80*
The code I was using is
```
http://www.webmasterworld.com/forum21/1205.htm
Call this javascript code from the HEAD section of each child page. The code creates a variable from the URL of the page, and then passes that variable in the new location's URL. This means a "master" frameset can load this exact page in the content section:
<SCRIPT LANGUAGE="JavaScript">
passpage = document.URL
if (top.location == self.location)
top.location.href="master.html?" + passpage
</script>
Then create just one "master.html" page. It holds the JavaScript code to decipher whatever URL is passed after the "?" and it writes that page into the content frame:
<html>
<head>
<title>Master Frameset</title>
</head>
<script language="JavaScript" type="text/javascript">
origURL = parent.document.URL
contentURL = origURL.substring(origURL.indexOf('?')+1, origURL.length)
document.write('<frameset cols="20%,80%"><frame src="leftnav.html" name="nav"><frame src="' + contentURL + '" name="content"><\/frameset>')
</script>
</html>
```
Thanks, Guillermo. | Sorry for delay.
Looks like the problem is in this little peace of javascript:
```
passpage = document.URL
if (top.location == self.location)
top.location.href="master.html?" + passpage
```
It should be:
```
passpage = window.location.pathname;
if (top.location == self.location) {
top.location.href="master.html?" + passpage;
}
```
You have to change that code in each page which you have in the link list. I think that should fix the problem. | I just checked the website and it seems to be working now. My guess is that there was no file located at <http://www.cpis.es/master.html> on server.
If the problem still exists please provide steps so we can reproduce it and see what went wrong. | force left (nav) frame when show some pages | [
"",
"javascript",
"html",
"iframe",
""
] |
I'm developing a media bookmarking site and am looking for a way to remember whether a user has bookmarked an item (without having to go to the DB every page load to check).
I haven't used PHP sessions before, but I'm thinking they would do the trick.
Would it make sense to do an initial DB call when the user logs in, grab all the items that a user has bookmarked and save an array of all the item ids to the user session?
Then when a page is loaded, for each of the 100 items on the page it would check whether that item's ID is in the session array (so we know whether to display the "bookmark" button or an indicator that they've already bookmarked it).
Just want to make sure this is a right strategy, or if there is a better way. Would this work fine even if there are 10,000 ids in the array? | Bear in mind that a common PHP strategy for increasing the robustness and speed of session management is to store session data in a database. You seem to be headed in the opposite direction. | As well you can take a look at Memcached extension - it uses server's memory as data storage. | PHP sessions for storing lots of data? | [
"",
"php",
"session",
""
] |
I've got an OR mapper (iBatis.Net) that returns an IList.
```
// IList<T> QueryForList<T>(string statementName, object parameterObject);
var data = mapper.QueryForList<Something>(statement, parameters);
```
I'm trying to use it in an webservice an want to return the data 1:1. Of course I can't return IList in a WebMethod, because it is an interface and therefore not serializable.
I found that the mapper is really returning an List. But I'm afraid to cast it to List because of course the mappers inner workings could change in future versions (and it just feels dirty).
So should I ...
```
a) return new List<Something>(data);
b) return (List<Something>)data;
c) // your solution here
```
Thanks a lot! | If it really is a `List<T>` but you want to protect against change and have it still work, then the most performant solution will be to attempt to cast it to a list, and if that fails then create a new list from its content, e.g.
```
var data = mapper.QueryForList<T>(statement, parameters);
var list = data as List<T> ?? new List<T>(data);
```
However, you mention that you can't return an interface because it's a web service. This may have been true with ASMX and the `XmlSerializer` class, but if you build the web service using WCF and use the `DataContractSerializer` then it will happily serialize collection interfaces (both as inputs to and outputs from the service). That type of change may be somewhat larger than you're looking for though! | Why should you serialize IList :) Just use it as a source for your own collection and serialize it:
```
var data = mapper.QueryForList<T>(statement, parameters);
var yourList = new List<T>(data);
//Serialize yourList here ))
``` | How to serialize an IList<T>? | [
"",
"c#",
".net",
"web-services",
".net-3.5",
"ibatis.net",
""
] |
I have problem with ActionLink.
I'd like to pass to my ActionLink parameter for my MessageController, for Edit action: to generate somthing like this /MessagesController/Edit/4
So I have ListView control with binding expression:
and how to pass this ID to ActionLink as parameter to my Controller Edit action?
This doesn't work:
, null) %> | Try this
```
<%= Html.ActionLink("my link", "Edit", "Message", new { id = ((Message)Container.DataItem).ID }) %>
```
You need to put it in the RouteData to get it to show up. Note I am assuming *id* is one of your route parts that is in your route definition. | In MVC you are not supposed to databind from the view in the way that you have. The data that you want to pass to the ActionLink method needs to be added to ViewData in your controller. Then in the view you retrieve it from ViewData:
```
<%= Html.ActionLink("My Edit Link", "Edit", "Message", new { id = ViewData["id"] }) %>
``` | How to bind data as parameter to ActionLink? | [
"",
"c#",
"asp.net-mvc",
""
] |
Assume the following type definitions:
```
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
```
How do I find out whether the type `Foo` implements the generic interface `IBar<T>` when only the mangled type is available? | By using the answer from TcKs it can also be done with the following LINQ query:
```
bool isBar = foo.GetType().GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IBar<>));
``` | You have to go up through the inheritance tree and find all the interfaces for each class in the tree, and compare `typeof(IBar<>)` with the result of calling `Type.GetGenericTypeDefinition` *if* the interface is generic. It's all a bit painful, certainly.
See [this answer](https://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class) and [these ones](https://stackoverflow.com/search?q=GetGenericTypeDefinition) for more info and code. | How to determine if a type implements a specific generic interface type | [
"",
"c#",
".net",
"reflection",
""
] |
I've been writing a java app on my machine and it works perfectly using the DB I set up, but when I install it on site it blows up because the DB is slightly different.
So I'm in the process of writing some code to verify that:
* A: I've got the DB details correct
* B: The database has all the Tables I expect and they have the right columns.
I've got A down but I've got no idea where to start with B, any suggestions?
Target DB is for the current client is Oracle, but the app can be configured to run on SQL Server as well. So a generic solution would be appreciated, but is not nessisary as I'm sure I can figure out how to do one from the other. | You'll want to query the information\_schema of the database, here are some examples for Oracle, every platform I am aware of has something similar.
<http://www.alberton.info/oracle_meta_info.html> | You might be able to use a database migration tool like LiquiBase for this -- most of these tools have some way of checking the database. I don't have first hand experience using it so it's a guess. | Verfying a database is as you expect it it be | [
"",
"java",
"database",
"oracle",
"verification",
""
] |
I have made a class which a form can inherit from and it handles form Location, Size and State. And it works nicely. Except for one thing:
When you maximize the application on a different screen than your main one, the location and size (before you maximized) gets stored correctly, but when it is maximized (according to its previous state) it is maximized on my main monitor. When I then restore it to normal state, it goes to the other screen where it was before. When I then maximize it again, it of course maximized on the correct screen.
So my question is... how can I make a form, when it is maximized, remember what screen it was maximized on? And how do I restore that when the form opens again?
---
## Kind of complete solution to problem
I accepted the answer which had a very good tip about how to if on screen. But that was just part of my problem, so here is my solution:
**On load**
1. First get stored `Bounds` and `WindowState` from whatever storage.
2. Then set the `Bounds`.
3. Make sure `Bounds` are visible either by `Screen.AllScreens.Any(ø => ø.Bounds.IntersectsWith(Bounds))` or `MdiParent.Controls.OfType<MdiClient>().First().ClientRectangle.IntersectsWith(Bounds)`.
* If it doesn't, just do `Location = new Point();`.
4. Then set window state.
**On closing**
1. Store `WindowState`.
2. If `WindowState` is `FormWindowState.Normal`, then store `Bounds`, otherwise store `RestoreBounds`.
And thats it! =)
## Some example code
So, as suggested by [Oliver](https://stackoverflow.com/users/57488/oliver), here is some code. It needs to be fleshed out sort of, but this can be used as a start for whoever wants to:
### PersistentFormHandler
Takes care of storing and fetching the data somewhere.
```
public sealed class PersistentFormHandler
{
/// <summary>The form identifier in storage.</summary>
public string Name { get; private set; }
/// <summary>Gets and sets the window state. (int instead of enum so that it can be in a BI layer, and not require a reference to WinForms)</summary>
public int WindowState { get; set; }
/// <summary>Gets and sets the window bounds. (X, Y, Width and Height)</summary>
public Rectangle WindowBounds { get; set; }
/// <summary>Dictionary for other values.</summary>
private readonly Dictionary<string, Binary> otherValues;
/// <summary>
/// Instantiates new persistent form handler.
/// </summary>
/// <param name="windowType">The <see cref="Type.FullName"/> will be used as <see cref="Name"/>.</param>
/// <param name="defaultWindowState">Default state of the window.</param>
/// <param name="defaultWindowBounds">Default bounds of the window.</param>
public PersistentFormHandler(Type windowType, int defaultWindowState, Rectangle defaultWindowBounds)
: this(windowType, null, defaultWindowState, defaultWindowBounds) { }
/// <summary>
/// Instantiates new persistent form handler.
/// </summary>
/// <param name="windowType">The <see cref="Type.FullName"/> will be used as base <see cref="Name"/>.</param>
/// <param name="id">Use this if you need to separate windows of same type. Will be appended to <see cref="Name"/>.</param>
/// <param name="defaultWindowState">Default state of the window.</param>
/// <param name="defaultWindowBounds">Default bounds of the window.</param>
public PersistentFormHandler(Type windowType, string id, int defaultWindowState, Rectangle defaultWindowBounds)
{
Name = string.IsNullOrEmpty(id)
? windowType.FullName
: windowType.FullName + ":" + id;
WindowState = defaultWindowState;
WindowBounds = defaultWindowBounds;
otherValues = new Dictionary<string, Binary>();
}
/// <summary>
/// Looks for previously stored values in database.
/// </summary>
/// <returns>False if no previously stored values were found.</returns>
public bool Load()
{
// See Note 1
}
/// <summary>
/// Stores all values in database
/// </summary>
public void Save()
{
// See Note 2
}
/// <summary>
/// Adds the given <paramref key="value"/> to the collection of values that will be
/// stored in database on <see cref="Save"/>.
/// </summary>
/// <typeparam key="T">Type of object.</typeparam>
/// <param name="key">The key you want to use for this value.</param>
/// <param name="value">The value to store.</param>
public void Set<T>(string key, T value)
{
// Create memory stream
using (var s = new MemoryStream())
{
// Serialize value into binary form
var b = new BinaryFormatter();
b.Serialize(s, value);
// Store in dictionary
otherValues[key] = new Binary(s.ToArray());
}
}
/// <summary>
/// Same as <see cref="Get{T}(string,T)"/>, but uses default(<typeparamref name="T"/>) as fallback value.
/// </summary>
/// <typeparam name="T">Type of object</typeparam>
/// <param name="key">The key used on <see cref="Set{T}"/>.</param>
/// <returns>The stored object, or the default(<typeparamref name="T"/>) object if something went wrong.</returns>
public T Get<T>(string key)
{
return Get(key, default(T));
}
/// <summary>
/// Gets the value identified by the given <paramref name="key"/>.
/// </summary>
/// <typeparam name="T">Type of object</typeparam>
/// <param name="key">The key used on <see cref="Set{T}"/>.</param>
/// <param name="fallback">Value to return if the given <paramref name="key"/> could not be found.
/// In other words, if you haven't used <see cref="Set{T}"/> yet.</param>
/// <returns>The stored object, or the <paramref name="fallback"/> object if something went wrong.</returns>
public T Get<T>(string key, T fallback)
{
// If we have a value with this key
if (otherValues.ContainsKey(key))
{
// Create memory stream and fill with binary version of value
using (var s = new MemoryStream(otherValues[key].ToArray()))
{
try
{
// Deserialize, cast and return.
var b = new BinaryFormatter();
return (T)b.Deserialize(s);
}
catch (InvalidCastException)
{
// T is not what it should have been
// (Code changed perhaps?)
}
catch (SerializationException)
{
// Something went wrong during Deserialization
}
}
}
// Else return fallback
return fallback;
}
}
```
**Note 1:** In the load method you have to look for previously stored `WindowState`, `WindowBounds` and other values. We use SQL Server, and have a `Window` table with columns for `Id`, `Name`, `MachineName` (for `Environment.MachineName`), `UserId`, `WindowState`, `X`, `Y`, `Height`, `Width`. So for every window, you would have one row with `WindowState`, `X`, `Y`, `Height` and `Width` for each user and machine. In addition we have a `WindowValues` table which just has a foreign key to `WindowId`, a `Key` column of type `String` and a `Value` column of type `Binary`. If there is stuff that is not found, I just leave things default and return false.
**Note 2:** In the save method you then, of course do the reverse from what you do in the Load method. Creating rows for `Window` and `WindowValues` if they don't exist already for the current user and machine.
### PersistentFormBase
This class uses the previous class and forms a handy base class for other forms.
```
// Should have been abstract, but that makes the the designer crash at the moment...
public class PersistentFormBase : Form
{
private PersistentFormHandler PersistenceHandler { get; set; }
private bool handlerReady;
protected PersistentFormBase()
{
// Prevents designer from crashing
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
Load += persistentFormLoad;
FormClosing += persistentFormFormClosing;
}
}
protected event EventHandler<EventArgs> ValuesLoaded;
protected event EventHandler<EventArgs> StoringValues;
protected void StoreValue<T>(string key, T value)
{
if (!handlerReady)
throw new InvalidOperationException();
PersistenceHandler.Set(key, value);
}
protected T GetValue<T>(string key)
{
if (!handlerReady)
throw new InvalidOperationException();
return PersistenceHandler.Get<T>(key);
}
protected T GetValue<T>(string key, T fallback)
{
if (!handlerReady)
throw new InvalidOperationException();
return PersistenceHandler.Get(key, fallback);
}
private void persistentFormLoad(object sender, EventArgs e)
{
// Create PersistenceHandler and load values from it
PersistenceHandler = new PersistentFormHandler(GetType(), (int) FormWindowState.Normal, Bounds);
PersistenceHandler.Load();
handlerReady = true;
// Set size and location
Bounds = PersistenceHandler.WindowBounds;
// Check if we have an MdiParent
if(MdiParent == null)
{
// If we don't, make sure we are on screen
if (!Screen.AllScreens.Any(ø => ø.Bounds.IntersectsWith(Bounds)))
Location = new Point();
}
else
{
// If we do, make sure we are visible within the MdiClient area
var c = MdiParent.Controls.OfType<MdiClient>().FirstOrDefault();
if(c != null && !c.ClientRectangle.IntersectsWith(Bounds))
Location = new Point();
}
// Set state
WindowState = Enum.IsDefined(typeof (FormWindowState), PersistenceHandler.WindowState) ? (FormWindowState) PersistenceHandler.WindowState : FormWindowState.Normal;
// Notify that values are loaded and ready for getting.
var handler = ValuesLoaded;
if (handler != null)
handler(this, EventArgs.Empty);
}
private void persistentFormFormClosing(object sender, FormClosingEventArgs e)
{
// Set common things
PersistenceHandler.WindowState = (int) WindowState;
PersistenceHandler.WindowBounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
// Notify that values will be stored now, so time to store values.
var handler = StoringValues;
if (handler != null)
handler(this, EventArgs.Empty);
// Save values
PersistenceHandler.Save();
}
}
```
And thats pretty much it. To use it, a form would just inherit from the PersistentFormBase. That would automatically take care of bounds and state. If anything else should be stored, like a splitter distance, you would listen for the `ValuesLoaded` and `StoringValues` events and in those use the `GetValue` and `StoreValue` methods.
Hope this can help someone! Please let me know if it does. And also, please provide some feedback if there is anything you think could be done better or something. I would like to learn =) | I found a solution to your problem by writing a little functio, that tests, if a poitn is on a connected screen.
The main idea came from
<http://msdn.microsoft.com/en-us/library/system.windows.forms.screen(VS.80).aspx>
but some modifications were needed.
```
public static bool ThisPointIsOnOneOfTheConnectedScreens(Point thePoint)
{
bool FoundAScreenThatContainsThePoint = false;
for(int i = 0; i < Screen.AllScreens.Length; i++)
{
if(Screen.AllScreens[i].Bounds.Contains(thePoint))
FoundAScreenThatContainsThePoint = true;
}
return FoundAScreenThatContainsThePoint;
}
``` | There's no built in way to do this - you'll have to write the logic yourself. One reason for this is that you have to decide how to handle the case where the monitor that the window was last shown on is no longer available. This can be quite common with laptops and projectors, for example. The [Screen](http://msdn.microsoft.com/en-us/library/system.windows.forms.screen(VS.80).aspx) class has some useful functionality to help with this, although it can be difficult to uniquely and consistently identify a display. | C#: How to make a form remember its Bounds and WindowState (Taking dual monitor setups into account) | [
"",
"c#",
"winforms",
"persistence",
""
] |
How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
```
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
``` | I think this can help you: [http://www.mattkruse.com/javascript/date/](https://web.archive.org/web/20090114044719/http://www.mattkruse.com/javascript/date/)
There's a `getDateFromFormat()` function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at [javascripttoolbox.com](https://web.archive.org/web/20090123134657/http://www.javascripttoolbox.com/lib/date/index.php) | Use `new Date(dateString)` if your string is compatible with [`Date.parse()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/parse). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a [new Date object](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date) with explicit values for year, month, date, hour, minute and second. | How can I convert string to datetime with format specification in JavaScript? | [
"",
"javascript",
"datetime",
"type-conversion",
""
] |
I have a Task object that has a collection of Label objects ... in the database the tables are called Task and Label.
There are a variety of ways to search for a Task, so using LINQ, I construct my LINQ query in an expression tree ... similar to the below code sample:
```
IQueryable<Data.Task> query = ctx.DataContext.Tasks;
if (criteria.Number > 0)
query = query.Where(row => row.Number == criteria.Number);
if (criteria.CustomerId != Guid.Empty)
query = query.Where(row => row.Project.CustomerId == criteria.CustomerId);
if (criteria.ProjectId != Guid.Empty)
query = query.Where(row => row.ProjectId == criteria.ProjectId);
var data = query.Select(row => TaskInfo.FetchTaskInfo(row));
this.AddRange(data);
```
This works great ... but now I would like to search for Tasks with a specific Label, for example, accounting or feature-request.
I am able to do this in LINQPad from a complete query:
```
from t in Tasks
join l in Labels on t.TaskId equals l.SourceId
where l.Name == "accounting"
select t
```
Is there anyway to do this using an expression tree? I'm stuck! Any help would be greatly appreciated! | I believe this should do it:
```
Tasks.Join(Labels.Where(l => l.Name == "accounting"), t => t.TaskId, l => l.SourceId, (t, l) => t)
``` | A "join" (not a "join ... into") clause in a query expression translates into a Join call. The tricky bit is transparent identifiers - only one sequence comes out of the join, and it's got to have both `t` and `l` in it (in your example) so the compiler does some magic.
I don't have much time to go into the details here, but it's probably best to just show you how your query expression is translated.
This:
```
from t in Tasks
join l in Labels on t.TaskId equals l.SourceId
where l.Name == "accounting"
select t
```
Is translated into:
```
Tasks.Join(Labels, t => t.TaskId, l => l.SourceId, (t, l) => new { t, l })
.Where(z => z.l.Name == "accounting")
.Select(z => z.t)
```
Note the introduction of "z" here - basically that contains both t and l from the original expression.
EDIT: David Morton's answer gives a more efficient way of doing it. His line is equivalent to:
```
from t in Tasks
join l in (from x in Labels where x.Name == "accounting")
on t.TaskId equals l.SourceId
select t
```
If you only have a select clause after the join, the compiler is able to skip the transparent identifier and put the projection directly as the last parameter to the Join call. | How to create a join in an expression tree for LINQ? | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
"join",
""
] |
I am a novice-intermediate programmer taking a stab at AJAX. While reading up on JavaScript I found it curious that most of the examples I've been drawing on use PHP for such an operation. I know many of you may argue that 'I'm doing it wrong' or 'JavaScript is a client-side language' etc. but the question stands. . .can you write a file in only JavaScript? | You can use something like [Google Gears](http://code.google.com/apis/gears/) to produce JS applications which are capable of storing data in a local cache or database. You can't read or write arbitrary areas of the disk though. (This was written in 2009 - [Google Gears is now deprecated](http://gearsblog.blogspot.com/2011/03/stopping-gears.html))
These days, you should be looking at the [local storage capabilities provided by HTML5](http://diveintohtml5.info/storage.html) | Yes, of course you can. It just depends on what API objects your javascript engine makes available to you.
However, odds are the javascript engine you're thinking about does not provide this capability. Definitely none of the major web browsers will allow it. | Is it possible to write to a file (on a disk) using JavaScript? | [
"",
"javascript",
"ajax",
""
] |
I'd like to call Update ... Set ... Where ... to update a field as soon as that evil ERP process is changing the value of another.
I'm running MS SQL. | I can't test, but i guess its a trigger like this
```
CREATE TRIGGER TriggerName ON TableName FOR UPDATE AS
IF UPDATE(ColumnUpdatedByERP)
BEGIN
UPDATE ...
END
```
-- Edit - a better version, thanks for comment Tomalak
```
CREATE TRIGGER TriggerName ON TableName FOR UPDATE AS
DECLARE @oldValue VARCHAR(100)
DECLARE @newValue VARCHAR(100)
IF UPDATE(ColumnUpdatedByERP)
BEGIN
SELECT @oldValue = (SELECT ColumnUpdatedByERP FROM Deleted)
SELECT @newValue = (SELECT ColumnUpdatedByERP FROM Inserted)
IF @oldValue <> @newValue
BEGIN
UPDATE ...
END
END
``` | You could use a trigger to update the other field.
Edit: I guess that may depend on what SQLesque database you are running. | How can I update a small field in a big SQL table if another field in the same row is changed by an external process? | [
"",
"sql",
"sql-server",
"event-handling",
"triggers",
""
] |
I have some strings that have been encrypted using the [PHP function `crypt()`](http://php.net/crypt).
The outputs look something like this:
```
$1$Vf/.4.1.$CgCo33ebiHVuFhpwS.kMI0
$1$84..vD4.$Ps1PdaLWRoaiWDKCfjLyV1
$1$or1.RY4.$v3xo04v1yfB7JxDj1sC/J/
```
While I believe crypt() is using the MD5 algorithm, the outputs are not valid MD5 hashes.
Is there a way of converting the produced hashes into valid MD5 hashes (16-byte hex values)?
---
*Update:*
Thanks for the replies so answers so far. I'm pretty sure the crypt function used is using some sort of MD5 algorithm. What I'm looking to do is convert the ouput that I have into an MD5 hash that looks something like the following:
```
9e107d9d372bb6826bd81d3542a419d6
e4d909c290d0fb1ca068ffaddf22cbd0
d41d8cd98f00b204e9800998ecf8427e
```
*(taken from [Wikipedia](http://en.wikipedia.org/wiki/MD5))*
Is there a way of converting from the hashes I have to ones like the above? | OK, so maybe this answer is a year late, but I'll give it a shot. In your own answer, you note that `crypt()` is using the FreeBSD MD5, which also does some interesting transformations on the salt before running the hash, so the result of what I'm about to give you will never quite match up with the results of a call to `md5()`. That said, the only difference between the output you are seeing and the format you are used to is that the output you are seeing is encoded as follows
```
$1$ # this indicates that it is MD5
Vf/.4.1. # these eight characters are the significant portion of the salt
$ # this character is technically part of the salt, but it is ignored
CgCo33eb # the last 22 characters are the actual hash
iHVuFhpw # they are base64 encoded (to be printable) using crypt's alphabet
S.kMI0 # floor(22 * 6 / 8) = 16 (the length in bytes of a raw MD5 hash)
```
To my knowledge, the alphabet used by crypt looks like this:
```
./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
```
So, with all of this borne in mind, here is how you can convert the 22 character crypt-base64 hash into a 32 character base16 (hexadecimal) hash:
First, you need something to convert the base64 (with custom alphabet) into a raw 16-byte MD5 hash.
```
define('CRYPT_ALPHA','./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
/**
* Decodes a base64 string based on the alphabet set in constant CRYPT_ALPHA
* Uses string functions rather than binary transformations, because said
* transformations aren't really much faster in PHP
* @params string $str The string to decode
* @return string The raw output, which may include unprintable characters
*/
function base64_decode_ex($str) {
// set up the array to feed numerical data using characters as keys
$alpha = array_flip(str_split(CRYPT_ALPHA));
// split the input into single-character (6 bit) chunks
$bitArray = str_split($str);
$decodedStr = '';
foreach ($bitArray as &$bits) {
if ($bits == '$') { // $ indicates the end of the string, to stop processing here
break;
}
if (!isset($alpha[$bits])) { // if we encounter a character not in the alphabet
return false; // then break execution, the string is invalid
}
// decbin will only return significant digits, so use sprintf to pad to 6 bits
$decodedStr .= sprintf('%06s', decbin($alpha[$bits]));
}
// there can be up to 6 unused bits at the end of a string, so discard them
$decodedStr = substr($decodedStr, 0, strlen($decodedStr) - (strlen($decodedStr) % 8));
$byteArray = str_split($decodedStr, 8);
foreach ($byteArray as &$byte) {
$byte = chr(bindec($byte));
}
return join($byteArray);
}
```
Now that you've got the raw data, you'll need a method to convert it to the base-16 format you're expecting, which couldn't be easier.
```
/**
* Takes an input in base 256 and encodes it to base 16 using the Hex alphabet
* This function will not be commented. For more info:
* @see http://php.net/str-split
* @see http://php.net/sprintf
*
* @param string $str The value to convert
* @return string The base 16 rendering
*/
function base16_encode($str) {
$byteArray = str_split($str);
foreach ($byteArray as &$byte) {
$byte = sprintf('%02x', ord($byte));
}
return join($byteArray);
}
```
Finally, since the output of crypt includes a lot of data we don't need (and, in fact, cannot use) for this process, a short and sweet function to not only tie these two together but to allow for direct input of output from crypt.
```
/**
* Takes a 22 byte crypt-base-64 hash and converts it to base 16
* If the input is longer than 22 chars (e.g., the entire output of crypt()),
* then this function will strip all but the last 22. Fails if under 22 chars
*
* @param string $hash The hash to convert
* @param string The equivalent base16 hash (therefore a number)
*/
function md5_b64tob16($hash) {
if (strlen($hash) < 22) {
return false;
}
if (strlen($hash) > 22) {
$hash = substr($hash,-22);
}
return base16_encode(base64_decode_ex($hash));
}
```
Given these functions, the base16 representation of your three examples are:
```
3ac3b4145aa7b9387a46dd7c780c1850
6f80dba665e27749ae88f58eaef5fe84
ec5f74086ec3fab34957d3ef0f838154
```
Of course, it is important to remember that they were always valid, just formatted differently. | I believe the answer to my original question is no, you can't convert from one format to the other.
The hashes generated by php crypt() appear to be generate by a version of the FreeBSD MD5 hash implementation created by Poul-Henning Kamp.
<http://people.freebsd.org/~phk/> | Can you convert the output of php crypt() to valid MD5? | [
"",
"php",
"hash",
"cryptography",
"md5",
"crypt",
""
] |
I have a relation mapping table like this:
attributeid bigint
productid bigint
To clean relations that are not used any more, I want to delete all recors where productid = x and attributeid not in (@includedIds), like the following example:
```
@attributetypeid bigint,
@productid bigint,
@includedids varchar(MAX)
DELETE FROM reltable
WHERE productid = @productid AND
attributetypeid = @attributetypeid AND
attributeid NOT IN (@includedids);
```
When running the SQL with the includedids param containing more than 1 id - like this: 25,26 - I get a SqlException saying:
Error converting data type varchar to bigint.
And that is of course due to the , in that varchar(max) param...
How should I construct my delete statement to make it work? | ```
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ListToTable] (
/*
FUNCTION ListToTable
Usage: select entry from listtotable('abc,def,ghi') order by entry desc
PURPOSE: Takes a comma-delimited list as a parameter and returns the values of that list into a table variable.
*/
@mylist varchar(8000)
)
RETURNS @ListTable TABLE (
seqid int not null,
entry varchar(255) not null)
AS
BEGIN
DECLARE
@this varchar(255),
@rest varchar(8000),
@pos int,
@seqid int
SET @this = ' '
SET @seqid = 1
SET @rest = @mylist
SET @pos = PATINDEX('%,%', @rest)
WHILE (@pos > 0)
BEGIN
set @this=substring(@rest,1,@pos-1)
set @rest=substring(@rest,@pos+1,len(@rest)-@pos)
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
SET @pos= PATINDEX('%,%', @rest)
SET @seqid=@seqid+1
END
set @this=@rest
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
RETURN
END
```
Run that script in your SQL Server database to create the function ListToTable. Now, you can rewrite your query like so:
```
@attributetypeid bigint,
@productid bigint,
@includedids varchar(MAX)
DELETE FROM reltable
WHERE productid = @productid AND
attributetypeid = @attributetypeid AND
attributeid NOT IN (SELECT entry FROM ListToTable(@includedids));
```
Where @includedids is a comma delimited list that you provide. I use this function all the time when working with lists. Keep in mind this function does not necessarily sanitize your inputs, it just looks for character data in a comma delimited list and puts each element into a record. Hope this helps. | Joel Spolsky answered a very similar question here: [Parameterize an SQL IN clause](https://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause/337817#337817)
You could try something similar, making sure to cast your attributetypeid as a varchar. | SQL Delete Where Not In | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.