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 en...
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 ```...
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 th...
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.su...
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 `/...
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 va...
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/q...
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 ...
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 da...
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/Image...
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 | | ...
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 ...
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], COU...
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( Use...
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...
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 an...
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"...
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...
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:sch...
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:** ``` myStr...
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 ...
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 runnin...
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 ...
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...
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 wit...
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: [![alt text](https://i.stack.imgur.com/EEhGd.jpg)](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/Fold...
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: ...
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 indexe...
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...
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 neith...
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 `RNGCrypt...
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 crypto...
`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...
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 bookd...
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...
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 tha...
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 insta...
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 ...
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 ar...
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 ...
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 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= ...
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 updat...
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()` ...
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 dire...
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 me...
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 usi...
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 s...
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 ...
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...
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 v...
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 be...
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 obj...
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 refer...
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 ...
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 ``` <im...
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, $A...
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 Examp...
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 c...
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 v...
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 ...
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 1...
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...
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"> <P...
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") ....
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...
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 o...
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 = getC...
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. (G...
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 ...
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); Ap...
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()) ...
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 l...
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 ...
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 po...
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....
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" %> <!...
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="hol...
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 [IHttp...
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...
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"...
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 p...
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 sen...
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. ...
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.m...
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 exec...
[`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...
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 ...
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 add...
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() | '...
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 eli...
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 c...
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 ("...
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...
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) ...
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 ...
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 MyDe...
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...
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 prob...
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 (F...
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 en...
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...
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)...
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....
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. ![alt text](https://media.techtarget.com/digitalguide/images/Misc/qe_iseries.gif) so, was wondering if anyone knows o...
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...
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` o...
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 m...
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, the...
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 t...
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)....
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 Na...
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 ...
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.inte...
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...
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 nee...
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 t...
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="{...
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 fi...
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 n...
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 gro...
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...
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 a...
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 `*` ope...
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> Fi...
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}; ...
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 [Configur...
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 d...
``` 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 *WindowsTok...
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 ...
[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-consol...
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...
> 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/Un...
* 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`, `\...
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/aw...
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...
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 u...
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 i...
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 s...
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) afte...
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...
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(te...
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 loc...
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 ...
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"> <scrip...
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/eke...
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...
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 ...
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, $con...
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 cau...
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 ...
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 co...
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&#xA;value_2 54&#xA;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: ...
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 transla...
I can't see why the `&#xA;` 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 cr...
replacing regex in java string, which contains `&#xA;` 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 containe...
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, ...
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 al...
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 javas...
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 your...
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...
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 ...
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 ...
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/HTM...
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...
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 optim...
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/pagefile...
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 determi...
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/t...
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-...
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 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) ? ...
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 configuratio...
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 th...
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 enu...
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: >...
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 b...
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 ...
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...
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 ran...
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-ma...
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() {...
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...
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 serve...
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.h...
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...
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 WebMe...
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> ...
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 doe...
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...
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 the...
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 ...
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(Poi...
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.micr...
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 [javas...
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 ...
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...
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 he...
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. . .c...
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/...
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...
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...
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 t...
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)...
``` 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)...
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", "" ]