Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it realistic to use the C# .Net class HttpListener as the foundation for a production caliber web server?
The http web service I need to host contains no .aspx or static files. All http responses are dynamic and generated in c# code that is invoked via a few switch statements which inspect a restful url format.
My thinking is that IIS is really a user-mode wrapper around the Windows o/s HTTP-SYS kernel module that does all the heavy duty network handling and so is HttpListener.
I already have a basic multithreaded web server running which is excellent for development because it starts in debug mode in an instance, now I am thinking do I need the overkill of IIS for production. A low memory footprint is another attraction. | You have two serious choices here. And no, coding your own Web Server with HttpListener isn't production-grade.
1) Use IIS. It has a ton of features for security, performance, and perhaps more importantly, *manageability*, that you would have to reinvent yourself. Like remote administration, logging, integrated Windows Security, etc.
2) Use WCF and create a ServiceHost to host your files. Then you will have to implement your own services and find a way to manage their lifetimes. You can do it, but again, if you're talking RESTFul web calls, IIS really is the way to go.
Manually rolling your own should be avoided. IIS has changed a lot in the past 10 years. It's by no means a big monolithic server anymore. They've modularized just about everything, especially in Windows 2008, so you get a lean and fast system. | Well, as it was said - try to use IIS at first.
HttpListener is not bad at all - that's fastest managed listener server you can have now (faster than TcpListener and faster than Socket class). And it's actually the same core as with IIS. But IIS has a lot of more things.
I can't say IIS is monolith - hosting usage shown that it became worse in Win2008 in terms of stability and management. But your hand-made solution can be much worse. And also don't forget - http.sys much more customizable than HttpListener. I.e. you can't do streaming with HttpListener, but you can do that with http.sys - [Question about HttpListener streaming](https://stackoverflow.com/questions/794207/how-to-flush-httplistener-response-stream)
But if you will have enough power as a developer - you can try to write up own http.sys wrapper and that is best approach of writing own web server in Windows. | Use HttpListener for a production caliber web server? | [
"",
"c#",
".net",
"webserver",
"httplistener",
""
] |
So I have a situation where I need to pass some parameters on url. In order to not have id=1 on the url, I added a simple encryption method to obfuscate the values. This has worked fine within the .Net land. Now however, I need to direct from a classic asp page to this .net page that is expecting the parameters to be encrypted. I really am not too familiar with encryption or classic asp and was hoping someone would be able to direct me to a good JS lib, or simply provide a classic asp version of this function? If there's anything wrong with the .Net code, I'd love to hear feedback on that as well.
Here's the encryption method:
```
public static string Encrypt(string Input)
{
try
{
key = Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));
var des = new DESCryptoServiceProvider();
Byte[] inputByteArray = Encoding.UTF8.GetBytes(Input);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception)
{
return "";
}
}
```
And here's the decryption method (I need this to decrypt the classic asp encrypted text):
```
public static string Decrypt(string Input)
{
try
{
key = Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));
var des = new DESCryptoServiceProvider();
var inputByteArray = Convert.FromBase64String(Input);
var ms = new MemoryStream();
var cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception)
{
return "";
}
}
```
Thanks for any help! | Don't mean to answer my own question, but I couldn't get the code added as a comment. Anyway, I ended up implementing RC4 on the client anyway. For anyone who may be interested (wth are you doing working in classic asp?? :) ) Here's the relevant code - hope it helps! As always, if anyone spots a problem with this snippet, please let me know!
Thanks,
Matt
```
Dim sbox(255)
Dim key(255)
Sub RC4Initialize(strPwd)
dim tempSwap
dim a
dim b
intLength = len(strPwd)
For a = 0 To 255
key(a) = asc(mid(strpwd, (a mod intLength)+1, 1))
sbox(a) = a
next
b = 0
For a = 0 To 255
b = (b + sbox(a) + key(a)) Mod 256
tempSwap = sbox(a)
sbox(a) = sbox(b)
sbox(b) = tempSwap
Next
End Sub
Function EnDeCrypt(plaintxt)
dim temp
dim a
dim i
dim j
dim k
dim cipherby
dim cipher
i = 0
j = 0
RC4Initialize "somesortofpassword"
For a = 1 To Len(plaintxt)
i = (i + 1) Mod 256
j = (j + sbox(i)) Mod 256
temp = sbox(i)
sbox(i) = sbox(j)
sbox(j) = temp
k = sbox((sbox(i) + sbox(j)) Mod 256)
cipherby = Asc(Mid(plaintxt, a, 1)) Xor k
dim h
h = hex(cipherby)
if Len(h) = 1 then
h = "0" & h
end if
cipher = cipher & h
Next
EnDeCrypt = cipher
End Function
``` | This isn't some simple translation! Classic ASP doesn't have access to the .NET Framework. You would need to do all of this in Win32 code.
You should package the C# code together as a COM component, which can then be accessed from the Classic ASP site. | Convert snippet from c# to vbscript | [
"",
"c#",
"asp.net",
"encryption",
"asp-classic",
""
] |
I have a query that counts member's wedding dates in the database.
```
SELECT
SUM(NumberOfBrides) AS [Wedding Count]
, DATEPART( wk, WeddingDate) AS [Week Number]
, DATEPART( year, WeddingDate) AS [Year]
FROM MemberWeddingDates
GROUP BY DATEPART(year, WeddingDate), DATEPART(wk, WeddingDate)
ORDER BY SUM(NumberOfBrides) DESC
```
How do I work out when the start and end of each week represented in the result set?
```
SELECT
SUM(NumberOfBrides) AS [Wedding Count]
, DATEPART(wk, WeddingDate) AS [Week Number]
, DATEPART(year, WeddingDate) AS [Year]
, ??? AS WeekStart
, ??? AS WeekEnd
FROM MemberWeddingDates
GROUP BY DATEPART(year, WeddingDate), DATEPART(wk, WeddingDate)
ORDER BY SUM(NumberOfBrides) DESC
``` | You can find the day of week and do a date add on days to get the start and end dates..
```
DATEADD(dd, -(DATEPART(dw, WeddingDate)-1), WeddingDate) [WeekStart]
DATEADD(dd, 7-(DATEPART(dw, WeddingDate)), WeddingDate) [WeekEnd]
```
You probably also want to look at stripping off the time from the date as well though. | Here is a `DATEFIRST` agnostic solution:
```
SET DATEFIRST 4 /* or use any other weird value to test it */
DECLARE @d DATETIME
SET @d = GETDATE()
SELECT
@d ThatDate,
DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Monday,
DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @d)) % 7, @d) Sunday
``` | Get the week start date and week end date from week number | [
"",
"sql",
"sql-server",
"date",
"sql-server-2005",
"week-number",
""
] |
**Modifed.**
```
DROP FUNCTION IF EXISTS PersonName;
DELIMITER |;
CREATE FUNCTION PersonName( personID SMALLINT )
RETURNS CHAR(20)
BEGIN
DECLARE pname CHAR(20) DEFAULT '';
SELECT name INTO pname FROM family WHERE ID=personID;
RETURN pname;
END;
|
DELIMITER ;
```
whats wrong with this code? i get following error with it.
> > There seems to be an error in your SQL query. The MySQL server error
> > output below, if there is any, may
> > also help you in diagnosing the
> > problem
>
> ERROR: Unknown Punctuation String @
> 102 STR: |; SQL: DROP FUNCTION IF
> EXISTS PersonName;# MySQL returned an
> empty result set (i.e. zero rows).
>
> DELIMITER |; DELIMITER |; DELIMITER |;
> DELIMITER |; DELIMITER |; DELIMITER |;
> DELIMITER |;
>
> SQL query:
>
> DELIMITER |;
>
> MySQL said: Documentation
> #1064 - You have an error in your SQL syntax; check the manual that
> corresponds to your MySQL server
> version for the right syntax to use
> near 'DELIMITER |' at line 1 | I would remove the semicolon after `END`.
```
...
END
|
DELIMITER ;
```
---
Re your comment, you can't use the current delimiter when declaring a new delimiter. That sounds confusing, but consider if you do this:
```
DELIMITER |;
```
Now MySQL would think the delimiter is "|;" (two characters, a pipe and a semicolon). If you think about it, `DELIMITER` *must* be treated in a special way by the MySQL client. It's the only statement that *can't* be followed by the current delimiter.
So when setting the delimiter to pipe, do this:
```
DELIMITER |
```
When setting it back to semicolon, do this:
```
DELIMITER ;
```
---
FWIW, I ran the following with no error on my local test database on MySQL 5.0.75:
```
DROP FUNCTION IF EXISTS PersonName;
DELIMITER |
CREATE FUNCTION PersonName( personID SMALLINT )
RETURNS CHAR(20)
BEGIN
DECLARE pname CHAR(20) DEFAULT '';
SELECT name INTO pname FROM family WHERE ID=personID;
RETURN pname;
END
|
DELIMITER ;
``` | Try this:
```
DROP FUNCTION IF EXISTS PersonName;
DELIMITER |
CREATE FUNCTION PersonName( personID SMALLINT )
RETURNS CHAR(20)
BEGIN
DECLARE pname CHAR(20) DEFAULT '';
SELECT name INTO pname FROM family WHERE ID=personID;
RETURN pname;
END;
|
DELIMITER ; /* <-- add a space between DELIMITER and the semicolon */
``` | Using a custom delimiter got error in MySQL? | [
"",
"sql",
"mysql",
"database",
"delimiter",
"mysql-error-1064",
""
] |
After running some hours my application fails in creating a new font object:
> CreateFontIndirect() returns NULL.
I know how to find memory leaks (i.e. using parallel inspector or another profiler - most of them include leak detection). But how can I locate a resource leak in Win32? | Grab yourself a copy of [GDI View](http://www.nirsoft.net/utils/gdi_handles.html) - this useful tool can show all the GDI objects used by your app, including details on the font name, size, etc. This has proved very handy in the past.
For Win32 apps you might want to look at the WTL framework - this wraps GDI objects with lightweight C++ classes that will handle object deletion for you. | It looks like the MSDN article ~~[Resource Leaks: Detecting, Locating, and Repairing Your Leaky GDI Code](http://msdn.microsoft.com/en-us/magazine/cc301756.aspx)~~([via archive.org](http://web.archive.org/web/20141228090817/http://msdn.microsoft.com/en-us/magazine/cc301756.aspx)) might provide you with an answer. | How do I find resource leaks in Win32? | [
"",
"c++",
"windows",
"visual-studio-2005",
"memory-leaks",
""
] |
When even mobile browsers have JavaScript, is it really necessary to consider potential script-free users? | Yes. Your web pages aren't just consumed by people: they're consumed by search engines, and crawlers, and screenscrapers. Most of those automatic tools don't support Javascript, and essentially none are going to generate UI events or look at deeply nested AJAX data. You want to have a simple static HTML fallback, if nothing else then so that your web pages are well indexed by the search engines.
Forget the crazies who disable Javascript; think of the robots! | ## Yes.
People can (and do) browse with javascript disabled. If your site will work without users having to explicitly enable javascript for you, that makes them happy.
Exactly how relevant depends on your target audience, of course. | Is graceful degradation in the absence of JavaScript still useful? | [
"",
"javascript",
"graceful-degradation",
""
] |
I am developing a library for serial communications with an FPGA via RS-422 port. This library is part of a bigger project.
I know I can test some parts of it, as the message generation. You set the inputs, and you can test if the array of bytes match the expected one. But, what if I wanted to make a more general test, how could I generate unit tests for it? do I have to write a simulator of the FPGA behaviour? is it possible to test the library in isolation? | I would say that testing with an emulator or mock is going to let you exercise your code paths much more easily than prodding the real thing.
Ideally one uses something pre-existing. Otherwise it may not be a small amount of effort to build the emulation. However, if you don't understand the protocol well enough to emulate it then you surely can't communicate with it :-) | You can make a mock class that would work as a simulator. Just make it so your write function processes the information you sent and saves the result on some kind of buffer, which could simply be a normal string. Then make a read function that reads the string, erases it and then returns it to you. | Unit testing a communications protocol | [
"",
"c#",
"unit-testing",
"testing",
"communication",
""
] |
What develepment environment do you use when you need to work on javascript?What options have as an Asp.net developer for working with javascript or jQuery in order to have possibilities to test,develop in realtime?
I tried to set up the intellisense to make it work the jQuery documentation, but that's not working.
Right now i'm using Firebug to test my scripts and also editing there,but for example i would like to view the markup and the console together but that's not possible on FireBug.
i don't think that's the best solution for that kind of work.
If you have any ideea how to solve my problem or do you have a suggestion please post it here.
Thanks!
**Update**
[JSBin](http://jsbin.com)
[JSFiddle](http://jsfiddle.net) are nice alternatives too. | Try Aptana.
It's free, it's awesome, and comes with JQuery & Prototype built-in.
It also has screencasts. | The essentials.
1. Your favorite text editor. That's [vim](http://www.vim.org/) for me.
2. [Google](http://www.google.com)
3. [Firebug](http://getfirebug.com)
4. [Web Developer's Toolbar](https://addons.mozilla.org/en-US/firefox/addon/60)
5. Two monitors (solves your whole "can't view source and the console together" problem) | Development Environment for Jquery and javascript | [
"",
"javascript",
"jquery",
"asp.net-ajax",
"development-environment",
""
] |
I have a form within my Asp.Net MVC application which returns a Null reference exception at the following line, but only after postback errors:
```
<%= Html.TextArea("Description", Model.Evt.Description ?? "")%>
```
The string Description is indeed null, but my expectation was that if `Model.evt.Description` is `null` then "" will be shown in the `TextArea`. Why is it doing this when it works fine on initially loading the form?
The only difference is that the type of ViewUserControl is is populated from a new object for initial load and the model object on postback reload.
What am I missing?
The Stack Trace is as follows:
```
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) +63
System.Web.Mvc.Html.TextAreaExtensions.TextAreaHelper(HtmlHelper htmlHelper, String name, Boolean useViewData, String value, IDictionary`2 implicitAttributes, IDictionary`2 explicitParameters, IDictionary`2 htmlAttributes) +261
System.Web.Mvc.Html.TextAreaExtensions.TextArea(HtmlHelper htmlHelper, String name, String value, IDictionary`2 htmlAttributes) +213
System.Web.Mvc.Html.TextAreaExtensions.TextArea(HtmlHelper htmlHelper, String name, String value) +61
ASP.views_events_eventform_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\Documents and Settings\Richard Box\My Documents\Visual Studio 2008\Projects\EventsManager\EventsManager\Views\Events\EventForm.ascx:64
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +59
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266
``` | My mistake, but I would say that the error information was pretty poor in this case, and I have no idea why this line was highlighted...
Within my Custom Model Binder I create an `Event` object and populate it with information from the form, however because the Event object is composed of several other objects some of which are `EntitySet`s I need to ensure that each of these are constructed before trying to populate them.
I should have noticed that this was not the case, and that an exception was raised in the model binder which is caught in the controller. The object and property which was raising the exception was completely unrelated to the `Model.Evt.Description` so I have no idea why this was highlighted in the error on displaying the view. | It looks like either Model or Evt is null, not actually the Description field. | Null Reference Exception and the ?? Operator | [
"",
"c#",
"asp.net-mvc",
""
] |
I have some idea from the previous posts that were talking about making a hash value for each `$arr[$i]`, and then compare the hash to get the unique array, but I don't know what I can do exactly.
My sample array Data:
```
$arr = [
[0, 1, 2, 3],
[4, 5, 2, 1],
[0, 0, 0, 0],
[0, 1, 2, 3]
];
```
I expected to return:
```
[
[0, 1, 2, 3],
[4, 5, 2, 1],
[0, 0, 0, 0]
]
``` | Quick and simple:
```
$arr = array_map('unserialize', array_unique(array_map('serialize', $arr)));
``` | PHP already offers a native way to directly remove duplicate rows in an array.
Pass in the `SORT_REGULAR` flag to the [`array_unique()`](https://www.php.net/manual/en/function.array-unique.php) call to tell PHP to not change the data type while evaluating values.
Code: ([Demo](https://3v4l.org/beujc))
```
var_export(array_unique($arr, SORT_REGULAR));
``` | Remove duplicate rows in a two dimensional array | [
"",
"php",
"arrays",
"multidimensional-array",
"duplicates",
""
] |
I have my own C++ `DateTime` class defined as:
```
class DateTime
{
public:
int year;
int month;
int day;
int hour;
int min;
int sec;
int millisec;
};
```
I have 2 `DateTime` which I need to compare to see which one is greater than (more recent) the other.
Is there any freely available C++ `DateTime` class that I can use to
1. Convert my DateTime class to their DateTime class
2. Their class should provide < , > , <= , >= operators for comparison
If a concrete example could be provided that would be great. Note that I need to compare down to millisecond.
I was thinking about **Boost** or **Qt**. Preferred **Boost** though. | See [Boost Date Time library](http://www.boost.org/doc/libs/1_39_0/doc/html/date_time.html)
And your class looks very much like [struct tm](http://en.wikipedia.org/wiki/Time.h#Data_types)
EDIT:
You're right that struct tm doesn't support millisecond precision.
Take a look at a [Boost example](http://www.boost.org/doc/libs/1_39_0/doc/html/date_time/examples.html#date_time.examples.time_math). Does that help? | You may want to check out [QDateTime](http://doc.trolltech.com/4.5/qdatetime.html) from Qt, wich has the required operators and ms accuracy.
Conversion from your class could be done via
```
class DateTime
{
public:
int year;
int month;
int day;
int hour;
int min;
int sec;
int millisec;
QDateTime toQDateTime() {
return QDateTime(QDate(year, month, day), QTime(hour, min, sec, millisec));
}
};
```
The other way around is similar ;-) | C++ DateTime class | [
"",
"c++",
"datetime",
"comparison",
""
] |
I am trying to create a query to sum total gifts given by a certain person, but to add a flag on the individual gift when the total giving hits $500 (I don't need to sum past that).
I have the Persons ID, the gift size, and the gift date. for example:
```
ID gift_date gift_amt
--------- ----------- --------------
1 1/6/09 500
2 1/9/09 200
2 1/15/09 65
3 1/26/09 140
2 2/10/09 600
3 3/7/09 200
```
I would like a flag to be shown in my query for ID# 1 on the row with gift\_date of 1/6/09, for ID#2 for gift date 2/10/09 and no flag for ID#3. | In `Oracle` and `PostgreSQL 8.4`:
```
SELECT q.*, CASE WHEN psum > 500 THEN 1 ELSE 0 END AS flag
FROM (
SELECT gd.*, SUM(gift_amt) OVER (PARTITION BY id ORDER BY gift_date) AS psum
FROM gift_date gd
) q
WHERE psum <= 500 - gift_amt
``` | Typically this would be done by the View (as in [Model-View-Controller](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller)). Most often this would be a grid control that has grouping functionality, rather than when the data is loaded. You would then load the data from the database as you showed above, and configured the view to display the grouped data. | SQL Running Sum with flags at certain amounts | [
"",
"sql",
"sum",
""
] |
I remember reading a book named:
> [Java Puzzlers Traps, Pitfalls, and Corner Cases](http://www.javapuzzlers.com)
that described odd behavior in Java code. Stuff that look completely innocent but in actuality perform something completely different than the obvious. One example was:
**(EDIT: This post is NOT a discussion on this particular example. This was the first example on the book I mentioned. I am asking for other oddities you might have encountered.)**
Can this code be used to identify if a number is odd or not?
```
public static boolean isOdd(int i) {
return i % 2 == 1;
}
```
And the answer is of course NO. If you plug a negative number into it you get the wrong answer when the number is odd. The correct answer was:
```
public static boolean isOdd(int i) {
return i % 2 != 0;
}
```
Now my question is **what are the weirdest, most counter intuitive piece of Java code you came across?** (I know it's not really a question, maybe I should post this as a community wiki, please advice on that as well) | One I [blogged about](http://www.billthelizard.blogspot.com/2009/06/java-puzzler.html) recently, given the following two classes:
```
public class Base
{
Base() {
preProcess();
}
void preProcess() {}
}
public class Derived extends Base
{
public String whenAmISet = "set when declared";
@Override void preProcess()
{
whenAmISet = "set in preProcess()";
}
}
```
what do you think the value of `whenAmISet` will be when a new `Derived` object is created?
Given the following simple main class:
```
public class Main
{
public static void main(String[] args)
{
Derived d = new Derived();
System.out.println( d.whenAmISet );
}
}
```
most people said it looks like the output should be "set in preProcess()" because the `Base` constructor calls that method, but it isn't. The `Derived` class members are initialized *after* the call to the `preProcess()` method in the `Base` constructor, which overwrites the value set in `preProcess()`.
The [Creation of New Class Instances](http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.5) section of the [JLS](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html) gives a very detailed explanation of the sequence of events that takes place when objects are created. | The most counterintuitive concept I came across is the PECS (Producer Extends, Consumer Super) from Josh Bloch. The concept is excellent, but what do you consider the consumer/producer in a situation - the method itself I would think at first. But no, the parameter collection is the P/C in this concept:
```
public <T> void consumeTs(Collection<? extends T> producer);
public <T> void produceTs(Collection<? super T> consumer);
```
Very confusing sometimes. | Java counter-intuitive code | [
"",
"java",
""
] |
I would like to have files named for example:
dd.mm.yyyy.log
How is this possible with log4net? | In your Log4net config file, use the following parameter with the RollingFileAppender:
```
<param name="DatePattern" value="dd.MM.yyyy'.log'" />
``` | ```
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs\" />
<datePattern value="dd.MM.yyyy'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
``` | Log4net rolling daily filename with date in the file name | [
"",
"c#",
".net",
"logging",
"filenames",
"log4net",
""
] |
This may be a silly question (with MSDN and all), but maybe some of you will be able to help me sift through amazing amounts of information.
I need to know the specifics of the implementations of common data structures and algorithms in C#. That is, for example, I need to know, say, how Linked Lists are handled and represented, how they and their methods are defined.
Is there a good centralized source of documentation for this (with code), or should I just reconstruct it? Have you ever had to know the specifics of these things to decide what to use?
Regards, and thanks. | Scott Mitchell has a great 6-part article that covers many .NET data structures:
[An Extensive Examination of Data Structures](http://msdn.microsoft.com/en-us/library/aa287104(VS.71).aspx)
For an algorithmic overview of data structures, I suggest reading *the* algorithm textbook: "Introduction to Algorithms" by Cormen, et al..
For details on each .NET data structure the MSDN page on that specific class is good.
When all of them fail to address issues, [Reflector](http://www.red-gate.com/products/reflector/) is always there. You can use it to dig through the actual source and see things for yourself. | If you really want to learn it, try making your own.
Googling for linked lists will give you a lot of hits and sample code to go off of. [Wikipedia](http://en.wikipedia.org/wiki/Linked_list) will also be a good resource. | Definition of C# data structures and algorithms | [
"",
"c#",
"algorithm",
"data-structures",
""
] |
I am new to C#, having previously been a Java developer. I am used to tools such as Eclipse, JUnit and Ant - are there C# equivalents I can use - or could you recommend some of the most popular tools? I've heard of Resharper and Nant. Please avoid documentation tools as I have asked this as a separate question.
Also in your opinion which ones are best? | Visual Studio replaces Eclipse. If you're a IntelliJ user, you should also install Resharper (although I recommend this even if you are not a IntelliJ user).
NAnt is the .NET equivalent for Ant
NUnit is the unit test tool of choice for .NET | * IDEs: Visual Studio (Express), MonoDevelop, SharpDevelop
* Unit-testing Frameworks: NUnit, mbUnit, TestDriven.NET
* Build Automation Tools: NAnt, MSBuild | What tools should I use for C# having previously been mainly a Java developer? | [
"",
"c#",
""
] |
I am interested in developing a portal-based application that works with [EAV models](http://en.wikipedia.org/wiki/Entity-Attribute-Value_model) and would like to know if there are any Java frameworks that aid in this type of development?
salesforce.com uses EAV and currently has twenty tables. The framework I seek should allow it to be configurable to different EAV implementations | [Sesame](http://www.openrdf.org/) is a more modern RDF API compared to Jena. [RDF](http://www.w3.org/RDF/) can be seen as a variant of the EAV model.
> The framework I seek should allow it
> to be configurable to different EAV
> implementations
Both Jena and Sesame are available as API layers for many RDF storage engines. | The [Jena library](http://jena.sourceforge.net/) is a standard for handling a set of RDF statements (Resource/Property/Object).
Other RDF engine: <http://mulgara.org/>, <http://sourceforge.net/projects/virtuoso/>... | Java Frameworks that support Entity-Attribute-Value Models | [
"",
"java",
"hibernate",
"persistence",
"entity-attribute-value",
""
] |
I'm using `Tamir.SharpSsh` to upload a file to a ssh server with the code below but I'm getting `System.IO.IOException: Pipe closed.` Any clue why?
```
SshTransferProtocolBase scp = new Scp(SSH_HOST, SSH_USER);
scp.Password = SSH_PASSWORD;
scp.Connect();
foreach (string file in files)
{
string remotePath = "incoming/" + new FileInfo(file).Name;
scp.Put(file, remotePath);
}
scp.Close();
```
Regards
/Niels | For future references: Apparently the server only accepted Sftp connections. So I changed to:
```
SshTransferProtocolBase scp = new Sftp(SSH_HOST, SSH_USER);
``` | I had exactly the same problem ("Pipe Closed") when trying to transfer files.
Changing to
```
Sftp scp = new Sftp(SSH_HOST, SSH_USER);
```
solved the problem.
Thanks
Stefano | C#/Tamir.SharpSsh: System.IO.IOException: Pipe closed | [
"",
"c#",
"ssh",
""
] |
> **Possible Duplicate:**
> [Properties vs Methods](https://stackoverflow.com/questions/601621/properties-vs-methods)
In method you can type some code and in properties too. For example I have a property Name. When class name changes I would like to get some data from database and change state of my object. I can add this code to set part of my property. Other solution is to change set part to private and add method called SetName and in this method add my code.
So what is the difference? When is the point when it's not good to put some code to getter / setter and when to create own method that is used to change my property and other parts of my class? | Here is a good set of **guidelines** for when to use properties vs methods from [Bill Wagner](http://dipankaronline.wordpress.com/2011/10/28/guidelines-for-when-to-use-properties-vs-methods-from-bill-wagner/) (fixed link)
* Use a Property when all these are true:
The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
* They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
* They should be settable in any order
* The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
* The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
* Use a method if the member returns an array.
* Repeated calls to the getter (without intervening code) should return the same value.
* Repeated calls to the setter (with the same value) should yield no difference from a single call.
* The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue. | Given a property like this
```
private string _name;
public string Name { get { return _name; } set { _name = value; } }
```
it is possible to write the following two methods:
```
public string get_Name() { return _name; }
public void set_Name(string value) { _name = value; }
```
which act identically. And in fact, this is exactly what the compiler does for you when you create a property.
Generally speaking, I steer away from properties when the code within them starts to feel "expensive", if that makes any sense. I want properties to feel like fields (with controlled side effects that happen at specific times), so they should be lightweight. | Method vs Property in C# - what's the difference | [
"",
"c#",
"class",
"oop",
"properties",
"methods",
""
] |
I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.
I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple in the list.
So, I might have
```
myList = [(20000, 11), (16000, 4), (14000, 9)...]
myDict = {11:20000, 9:14000, ...}
```
I want to remove each (v, k) tuple from the list.
Currently I am doing:
```
for k, v in myDict.iteritems():
myList.remove((v, k))
```
Removing 838 tuples from the list containing 20,000 tuples takes anywhere from 3 - 4 seconds. I will most likely be removing more like 10,000 tuples from a list of 1,000,000 so I need this to be faster.
Is there a better way to do this?
I can provide code used to test, plus pickled data from the actual application if needed. | You'll have to measure, but I can imagine this to be more performant:
```
myList = filter(lambda x: myDict.get(x[1], None) != x[0], myList)
```
because the lookup happens in the dict, which is more suited for this kind of thing. Note, though, that this will create a new list before removing the old one; so there's a memory tradeoff. If that's an issue, rethinking your container type as jkp suggest might be in order.
**Edit**: Be careful, though, if `None` is actually in your list -- you'd have to use a different "placeholder." | To remove about 10,000 tuples from a list of about 1,000,000, if the values are hashable, the fastest approach should be:
```
totoss = set((v,k) for (k,v) in myDict.iteritems())
myList[:] = [x for x in myList if x not in totoss]
```
The preparation of the set is a small one-time cost, wich saves doing tuple unpacking and repacking, or tuple indexing, a lot of times. Assignign to `myList[:]` instead of assigning to `myList` is also semantically important (in case there are any other references to `myList` around, it's not enough to rebind just the name -- you really want to rebind the *contents*!-).
I don't have your test-data around to do the time measurement myself, alas!, but, let me know how it plays our on your test data!
If the values are not hashable (e.g. they're sub-lists, for example), fastest is probably:
```
sentinel = object()
myList[:] = [x for x in myList if myDict.get(x[0], sentinel) != x[1]]
```
or maybe (shouldn't make a big difference either way, but I suspect the previous one is better -- indexing is cheaper than unpacking and repacking):
```
sentinel = object()
myList[:] = [(a,b) for (a,b) in myList if myDict.get(a, sentinel) != b]
```
In these two variants the sentinel idiom is used to ward against values of `None` (which is not a problem for the preferred set-based approach -- if values are hashable!) as it's going to be way cheaper than `if a not in myDict or myDict[a] != b` (which requires two indexings into myDict). | Python: remove lots of items from a list | [
"",
"python",
""
] |
In a web application, I want to load all assemblies in the /bin directory.
Since this can be installed anywhere in the file system, I can't gaurantee a specific path where it is stored.
I want a List<> of Assembly assembly objects. | Well, you can hack this together yourself with the following methods, initially use something like:
```
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
```
to get the path to your current assembly. Next, iterate over all DLL's in the path using the Directory.GetFiles method with a suitable filter. Your final code should look like:
```
List<Assembly> allAssemblies = new List<Assembly>();
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
foreach (string dll in Directory.GetFiles(path, "*.dll"))
allAssemblies.Add(Assembly.LoadFile(dll));
```
Please note that I haven't tested this so you may need to check that dll actually contains the full path (and concatenate path if it doesn't) | To get the bin directory, `string path = Assembly.GetExecutingAssembly().Location;` does **NOT** always work (especially when the executing assembly has been placed in an ASP.NET temporary directory).
Instead, you should use `string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");`
Further, you should probably take the FileLoadException and BadImageFormatException into consideration.
Here is my working function:
```
public static void LoadAllBinDirectoryAssemblies()
{
string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin"); // note: don't use CurrentEntryAssembly or anything like that.
foreach (string dll in Directory.GetFiles(binPath, "*.dll", SearchOption.AllDirectories))
{
try
{
Assembly loadedAssembly = Assembly.LoadFile(dll);
}
catch (FileLoadException loadEx)
{ } // The Assembly has already been loaded.
catch (BadImageFormatException imgEx)
{ } // If a BadImageFormatException exception is thrown, the file is not an assembly.
} // foreach dll
}
``` | how to load all assemblies from within your /bin directory | [
"",
"c#",
"assemblies",
""
] |
I have a .NET application where, given a noun, I want it to correctly prefix that word with "a" or "an". How would I do that?
Before you think the answer is to simply check if the first letter is a vowel, consider phrases like:
* an honest mistake
* a used car | 1. Download Wikipedia
2. Unzip it and write a quick filter program that spits out only article text (the download is generally in XML format, along with non-article metadata too).
3. Find all instances of a(n).... and make an index on the following word and all of its prefixes (you can use a simple suffixtrie for this). This should be case sensitive, and you'll need a maximum word-length - 15 letters?
4. (optional) Discard all those prefixes which occur less than 5 times or where "a" vs. "an" achieves less than 2/3 majority (or some other threshholds - tweak here). Preferably keep the empty prefix to avoid corner-cases.
5. You can optimize your prefix database by discarding all those prefixes whose parent shares the same "a" or "an" annotation.
6. When determining whether to use "A" or "AN" find the longest matching prefix, and follow its lead. If you didn't discard the empty prefix in step 4, then there will *always* be a matching prefix (namely the empty prefix), otherwise you may need a special case for a completely-non matching string (such input should be very rare).
You probably can't get much better than this - and it'll certainly beat most rule-based systems.
**Edit:** I've [implemented this in JS/C#](https://github.com/EamonNerbonne/a-vs-an/). You can [try it in your browser](https://eamonnerbonne.github.io/a-vs-an/AvsAnDemo/), or download the small, reusable javascript implementation it uses. The .NET implementation is package [`AvsAn` on nuget](https://www.nuget.org/packages/AvsAn/). The implementations are trivial, so it should be easy to port to any other language if necessary.
Turns out the "rules" are quite a bit more complex than I thought:
* it's **an** unanticipated result but it's **a** unanimous vote
* it's **an** honest decision but **a** honeysuckle shrub
* Symbols: It's **an** 0800 number, or **an** ∞ of oregano.
* Acronyms: It's **a** NASA scientist, but **an** NSA analyst; **a** FIAT car but **an** FAA policy.
...which just goes to underline that a rule based system would be tricky to build! | You need to use a list of exceptions. I don't think all of the exceptions are well defined, because it sometimes depends on the accent of the person saying the word.
One stupid way is to ask Google for the two possibilities (using the one of the search APIs) and use the most popular:
* <http://www.google.co.uk/search?q=%22a+europe%22> - 841,000 hits
* <http://www.google.co.uk/search?q=%22an+europe%22> - 25,000 hits
Or:
* <http://www.google.co.uk/search?q=%22a+honest%22> - 797,000 hits
* <http://www.google.co.uk/search?q=%22an+honest%22> - 8,220,000 hits
Therefore "a europe" and "an honest" are the correct versions. | How can I correctly prefix a word with "a" and "an"? | [
"",
"c#",
"nlp",
"linguistics",
""
] |
Is it possible to output values to the console from within a class library?
For example
```
Console App -> calls method in -> assembly > function
```
Is it possible to write a console.out method in the function of the assembly?
I know in web its possible to get the httpcontext, and do a response.write. | Yup, `Console.WriteLine` etc will work just fine in a class library... but there's no guarantee that anything is *listening* to the console. If you use it from a WinForms app or a web app, that output may well go absolutely nowhere...
Have you thought of using a logging library such as [log4net](http://logging.apache.org/log4net/index.html) instead? | It depends on what type of application is going to use your class library. If it is used in a console application, then the output will be printed to the console. If it is a WinForms, Windows Service or ASP.NET application the output will be ignored. | Possible to output to console from within a class library C#? | [
"",
"c#",
"console",
""
] |
Interface vs. Base class is still a fairly gray area to me. I'm reading a book on ASP.NET 3.5 Enterprise Development and the author states that all tables will have the following fields:
```
InsertDate
InsertENTUserAccountId
UpdateDate
UpdateENTUserAccountId
Version
```
If this were me coding the above requirement, I would create a base business object class that contained these fields, and all business objects would inherit from it. However, the author has created these as an Interface instead. Bad idea? Good idea? Doesn't matter?
**Update**
There is a base class that implements this Interface. It appears that all business objects would then inherit from the base. But even still, I would have just put this Interface in the base class...? | By using an interface you are required to implement all those properties in all classes that implement the interface. If the implementation is the same for all, this is a lot of duplicated code. This can be mitigated by having a base class implement the interface.
By using a base class you can share the same implementation among all subclasses. Problems arise if you need to subclass something else, as .NET does not allow multiple inheritance. This way you will have to directly implement the interface (probably using composition). | Well, an interface is usually preferred as it allows greater flexibility and abstraction - but you can do both, by having your `abstract` base-class implement the interface. Then 95% of the time you use the base-class, and when you need something different you just use the interface.
Just don't touch the base-class from your business code... only the interface. The base-class is an implementation detail only. | Should this code have been a Base class instead of an Interface? | [
"",
"c#",
"asp.net",
"oop",
""
] |
I know that this won't directly invert a colour, it will just 'oppose' it. I was wondering if anyone knew a simple way (a few lines of code) to invert a colour from any given colour?
At the moment I have this (which isn't exactly the definition of an invert, because if I pass it a grey / gray colour it will return something extremely similar e.g. 127, 127, 127):
```
const int RGBMAX = 255;
Color InvertMeAColour(Color ColourToInvert)
{
return Color.FromArgb(RGBMAX - ColourToInvert.R,
RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B);
}
``` | It depends on what do you mean by "inverting" a color
Your code provides a "negative" color.
Are you looking for transform red in cyan, green in purple, blue in yellow (and so on) ? If so, you need to convert your RGB color in [HSV](http://en.wikipedia.org/wiki/HSL%5Fand%5FHSV) mode (you will find [here](http://en.wikipedia.org/wiki/HSL%5Fand%5FHSV#Conversion%5Ffrom%5FRGB%5Fto%5FHSL%5For%5FHSV) to make the transformation).
Then you just need to invert the Hue value (change `Hue` by `360-Hue`) and convert back to RGB mode.
EDIT: as Alex Semeniuk has mentioned, changing `Hue` by `(Hue + 180) % 360` is a better solution (it does not invert the Hue, but find the opposite color on the color circle) | You can use :
```
MyColor=Color.FromArgb(MyColor.ToArgb()^0xffffff);
```
It will invert MyColor. | How do I invert a colour? | [
"",
"c#",
".net",
"colors",
"system.drawing.color",
""
] |
I've been playing with various ways of doing literate programming in Python. I like [`noweb`](http://www.cs.tufts.edu/~nr/noweb/), but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs.
Is there a good literate programming tool that:
1. Runs on Windows
2. Allows me to set the indentation of the chunks when they're used, not when they're written
3. Still lets me work in Emacs
Thanks!
---
Correction: `noweb` *does* allow me to indent later --- I misread the paper I found on it.
> > > By default, `notangle` preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant
That leaves me with only the "Runs on Windows" problem. | I did this:
<http://sourceforge.net/projects/pywebtool/>
You can get any number of web/weave products that will help you construct a document and code in one swoop.
You can -- pretty easily -- write your own. It's not rocket science to yank the Python code blocks out of RST source and assemble it. Indeed, I suggest you write your own Docutils directives to assemble the Python code from an RST source document.
You run the RST through docutils rst2html (or Sphinx) to produce your final HTML report.
You run your own utility on the same RST source to extract the Python code blocks and produce the final modules. | I have written Pweave <http://mpastell.com/pweave>, that is aimed for dynamic report generation and uses noweb syntax. It is a pure python script so it also runs on Windows. It doesn't fix your indent problem, but maybe you can modify it for that, the code is really quite simple. | What's the best way to do literate programming in Python on Windows? | [
"",
"python",
"windows",
"literate-programming",
"noweb",
""
] |
What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?
**Note:** By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005"). | Since ECMAScript 2017 we have [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart):
```
const padded = (.1 + "").padStart(6, "0");
console.log(`-${padded}`);
```
### Before ECMAScript 2017
With [toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString):
```
var n=-0.1;
var res = n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false});
console.log(res);
``` | I can't believe all the complex answers on here... Just use this:
```
var zerofilled = ('0000'+n).slice(-4);
```
```
let n = 1
var zerofilled = ('0000'+n).slice(-4);
console.log(zerofilled)
``` | How can I pad a value with leading zeros? | [
"",
"javascript",
"leading-zero",
"zerofill",
""
] |
I've got a checkbox inside a table, and when you click on it, it'll change the background colour accordingly like so...
```
$("#table tr td :checkbox").bind("click change", function() {
$this = $(this); // cache the jquery object
if($this.is(':checked')) { $this.closest('tr').css('background-color', 'lightyellow'); }
else { $this.closest('tr').css('background-color', '#fff'); }
});
```
That works just fine, however, I figured I'd like to go one better, so anywhere on the table row you click, it'll check the box and highlight the row.
I tried using this code, but it doesn't work unfortunately:
```
$("table tr").bind("click", function() {
$(this).parents("tr").find(":checkbox").attr('checked');
});
```
And here's the HTML code (removed excessive stuff to improve readability...
```
<td>Name</td>
<td>Description</td>
<td><input type="checkbox"></td>
```
Any help would be very much appreciated, thank you! | The event your handling is the tr click.
The parent is the table so that will not help. All you need to do is use find() from the this context.
I would use .live to avoid multiple event handlers when one will do.
Assuming you only have one checkbox in the row then use the following.
(note it uses tr's inside tbody to avoid running this on thead rows)
```
$("table>tbody>tr").live("click", function() {
$(this).find(":checkbox").attr('checked', 'checked');
});
```
UPDATE
If you want to toggle it try something like
```
$("table>tbody>tr").live("click", function(ev) {
var $checkbox = $(this).find(":checkbox");
//check to see we have not just clicked the actual checkbox
if ( !$(ev.target).is(':checkbox') ){
$checkbox.is(':checked') ? $checkbox.removeAttr('checked')
: $checkbox.attr('checked', 'checked')
}
});
``` | You want to change this:
```
$(this).parents("tr").find(":checkbox").attr('checked');
```
to this:
```
$(this).parents("tr").find(":checkbox").attr('checked', 'checked');
```
Otherwise all you're doing is *reading* the `checked` attribute, not setting it. | Finding the next input (of a parent?) with jQuery | [
"",
"javascript",
"jquery",
"input",
""
] |
Good day pythonians,
I want to make a custom dictionary with two main features:
1. All keys are declared on creation
2. It is impossible to add new keys or modify current ones (values are still modifiable)
Right now code is this:
```
class pick(dict):
"""This will make delicious toffee when finished"""
def __init__(self, *args):
dict.__init__(self)
for arg in args:
self[arg] = None
```
Any help is much appreciated.
**upd:**
While solution is what I was looking for there is one problem:
dictionary calls the `__setitem__` to add the items on the initialization and not finding the keys it raises the error.
```
cupboard = pick('milk') #raises error
```
**upd1:**
all solved, thank you very much. | Override the `__setitem__` method with your desired behavior, call `dict.__setitem__(self, key, value`) to modify the base dictionary without going through your base logic.
```
class ImmutableDict(dict):
def __setitem__(self, key, value):
if key not in self:
raise KeyError("Immutable dict")
dict.__setitem__(self, key, value)
d = ImmutableDict(foo=1, bar=2)
d['foo'] = 3
print(d)
d['baz'] = 4 # Raises error
```
You'll also need to override `dict.update()` and `setdefault()` to avoid addition of keys. And possibly `dict.__delitem__()`, `dict.clear()`, `dict.pop()` and `dict.popitem()` to avoid removal of keys. | Something like
```
class UniqueDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def __setitem__(self, name, value):
if name not in self:
raise KeyError("%s not present")
dict.__setitem__(self, name, value)
``` | Locking a custom dictionary | [
"",
"python",
"dictionary",
"locking",
""
] |
i made a state machine and would like it to take advantage of generics in java. currently i dont see the way i can make this work and get *pretty* looking code. im sure this design problem has been approached many times before, and im looking for some input. heres a rough outline.
```
class State { ... }
```
only one copy of each distinct state object (mostly anonymous classes tied to static final variables), it has custom data for each state. each state object has a state parent (there is one root state)
```
class Message { ... }
```
each message is created separately and each one has custom data. they may subclass each other. there is one root message class.
```
class Handler { ... }
```
each handler is created only once and deals with a specific state / message combo.
```
class StateMachine { ... }
```
currently keeps track of the current state, and a list of all (`State`,`Message`) -> `Handler` mappings. it has other functionality as well. i am trying to keep this class generic and subclass it with type parameters as its used a bunch of times in my program, and each time with a different set of `Message`'s / `State`'s / and `Handler`'s. different `StateMachine`'s will have different parameters to their handlers.
## Approach A
have the state machine keep track of all mappings.
```
class StateMachine<MH extends MessageHandler> {
static class Delivery {
final State state;
final Class<? extends Message> msg;
}
HashMap<Delivery, MH> delegateTable;
...
}
class ServerStateMachine extends StateMachine<ServerMessageHandler> {
...
}
```
allows me to have custom handler methods for this particular state machine. the parameters for the handler.process method can be overwritten. However, the handler cannot be parameterized by the message type.
**Problem:** this involves using the `instanceof` sanity check for each message handler (making sure it is getting the message it is expecting).
## Approach B
lets make each message handler parameterized by message type
```
class MessageHandler<M extends Message> {
void process(M msg) { .... }
}
```
**Problem:** type erasure will prevent me from storing these in a nice hashmap since all the `MessageHandler`'s will be typed differently. if i can store them in a map, i wont be able to retreive them and call them with the proper arguements.
## Approach C
have the state object handle all messages.
```
class State<M extends Message> { ... }
class ServerState<M extends ServerMessage> extends State<M> { ... }
```
i have message handlers tied to specific state machine states (by putting them inside), (each instance of a state machine would have its own list of valid states), which allows the handlers to be of a specific type. (server state machine -> server message handler).
**Problem:** each state can only handle one message type. you also lose the idea that parent state's can handle different messages than child states. type erasure also prevents the `StateMachine` from calling current states process methods.
## Approach D
have the message's process themselves based on state.
**Problem:** never really considered, since each message should have a different handler based on the current state machine state. the sender will not know the current `StateMachine`'s state.
## Approach E
forget about generics and hard code state / message handling with a switch statement.
**Problem:** *sanity*
## Unsafe Solution:
Thanks for your input everybody, i think the problem was i did not reduce this to good problem (too much discussion) heres what i have now.
```
public class State { }
public class Message { }
public class MessageHandler<T extends Message> { }
public class Delivery<T extends Message> {
final State state;
final Class<T> msgClass;
}
public class Container {
HashMap<Delivery<? extends Message>, MessageHandler<? extends Message>> table;
public <T extends Message> add(State state, Class<T> msgClass, MessageHandler<T> handler) {
table.put(new Delivery<T>(state, msgClass), handler);
}
public <T extends Message> MessageHandler<T> get(State state, T msg) {
// UNSAFE - i cannot cast this properly, but the hashmap should be good
MessageHandler<T> handler = (MessageHandler<T>)table.get(new Delivery<T>(state, msg.getClass()));
return handler;
}
}
``` | For approach B, don't use a "nice" hashmap. Instead, write a heterogenous typesafe container mapping handlers to Class objects:
```
interface Handler<T extends Message> {
...}
interface Message {...}
interface HandlerContainer {
<T extends Message> void register(Class<T> clazz, Handler<T> handler);
<T extends Message> Handler<T> getHandler(T t);
}
class HandlerContainerImpl implements HandlerContainer {
private final Map<Class<?>,Handler<?>> handlers = new HashMap<Class<?>,Handler<?>>();
<T extends Message> void register(Class<T> clazz, Handler<T> handler) {
if (clazz==null || handler==null) {
throw new IllegalArgumentException();
}
handlers.put(clazz,handler);
}
//Type safety is assured by the register message and generic bounds
@SuppressWarnings("unchecked")
<T extends Message> Handler<T> getHandler(T t) {
return (Handler<T>)handlers.get(t.getClass());
}
}
``` | Approach E. Forget about generics, and use interfaces.
```
class Message { ... }
class State { ... }
class Machine {
static State handle(State current, Message msg) {
...
}
}
class CustomMessage extends Message { ... }
class CustomState extends State { ... }
class CustomMachine {
static CustomState handle(CustomState current, CustomMessage msg) {
// custom cases
...
// default: generic case
return Machine.handle(current, msg);
}
}
``` | java generics design problem (state machine) | [
"",
"java",
"design-patterns",
"generics",
"state-machine",
""
] |
Im working on a project at work which is pretty much a commissioning manager and i cant seem to figure out how to link the Items table properly in linq to sql.
I have a package detail table that has (among other things)
```
DepartmentID, CategoryID, ItemID
```
And the Items table (is actually a database view as its from a different database and is read only in this app) also have these 3 fields but when i add an association with these 3 fields it doesnt add that as a property object ot the PackageDetail class
am i doing something wrong with the association? all the single ones im doing work fine... | I don't believe that Linq-to-SQL can properly model an association with a composite key:
[Is it beneficial to use multicolumn (composite) primary keys when using Linq to SQL?](https://stackoverflow.com/questions/647146/is-it-beneficial-to-use-multicolumn-composite-primary-keys-when-using-linq-to-s)
However, you can still load objects with composite keys in a Linq-to-SQL query using an anonymous object as the (single) key:
<http://msdn.microsoft.com/en-us/library/bb399391.aspx> | have marked those ID fields as Primary keys? Make sure you assign the necessary columns as primary keys and this should work fine. Hope it helps | linq to sql linking objects by multiple ID fields | [
"",
"c#",
"linq-to-sql",
""
] |
In my BL (will be a public API), I am using ICollection as the return types in my Find methods, like:
```
public static ICollection<Customer> FindCustomers()
{
Collection<Customer> customers = DAL.GetCustomers();
return customers;
}
```
Note the use of ICollection instead of Collection<>.
Now in my GUI, I need to cast the results back to Collection, like:
```
Collection<Customer> customers = (Collection<Customer>)BL.FindCustomers();
```
This is because I need to use some Collection<> specific methods on my returned list, which I cannot do with ICollection<>.
Is this the correct usage? Or should I simply change the return type from Collection<> instead to ICollection<> in order to avoid this casting?
Secondly, I did not use IEnumerable because it is more generic than ICollection and does not even have simple properties like Count. And I really don’t see a point in generalizing the return types here. Am I missing something important? | The whole point of using ICollection is to be more generic and hide more information, which is a good thing.
But if you need to convert it back it has become pointless and you might as well return the more functional Collection< > instead. | The only reason you would want to return ICollection is for loose coupling and inheritance purpouses. If there is only 1 version of your method (which there is becaue its static) youll always know the return type (Collection) and there is no need to make it an ICollection. However if you were using in a family of classes, there could be a virtual or abstract method that return and ICollection, then in the subclass implementations one can return a Collection or a FunkyCollection or any object that implements the interface, so this gives you a lot more f lexibility that saying you can only return a Collection. But for your purposes you should prolly just make the return type Collection and not ICollection because its a static method that wont be overriden. Also it causes less confusion to the user because they dont need to cast. | Question regarding return types with collections | [
"",
"c#",
"collections",
""
] |
I'm making a custom ListCellRenderer. I know that you can have different dimensions for each individual cell. But now I want to have a different dimension for the selected cell. Somehow, the JList is caching the dimension for each individual cell the first time it has to calculate bounds for each cell.
This is my code:
```
public class Test {
static class Oh extends JPanel {
public Oh() {
setPreferredSize(new Dimension(100, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
static class Yeah extends JPanel {
private boolean isSelected;
public Yeah(boolean isSelected) {
setPreferredSize(new Dimension(100, 100));
this.isSelected = isSelected;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//setSize(100, 100); // doesn't change the bounds of the component
//setBounds(0, 0, 100, 100); // this doesn't do any good either.
if (isSelected) g.setColor(Color.GREEN);
else g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setSize(800, 500);
Vector<Integer> ints = new Vector<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
JList list = new JList(ints);
list.setCellRenderer(new ListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected || ((Integer) value) == 42) return new Yeah(isSelected);
else return new Oh();
}
});
//list.setPrototypeCellValue(null);
//list.setFixedCellHeight(-1);
f.add(new JScrollPane(list));
f.setVisible(true);
}
}
```
In the comments you can see what I've already tried.
I've already searched quite long and found a lot of useless articles, some of them touch the ListCellRenderer/dynamic height thing, but they only work because the height stays the same for the individual cells. My heights are changing, so how do I do this? | Thanks to Rastislav Komara I've been able to solve this quite easily:
I've created an inner class that extends BasicListUI and created public method that is called on ListSelectionListener.valueChanged:
```
private class MyRenderer implements ListCellRenderer {
public int listSelectedIndex = -1;
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if (index == listSelectedIndex)
return new Yeah(isSelected);
else
return new Oh();
}
}
MyRenderer lcr = new MyRenderer();
private class MyListUI extends BasicListUI {
public void triggerUpdate() {
lcr.listSelectedIndex = list.getSelectedIndex();
updateLayoutState();
list.revalidate();
}
}
```
The updateLayoutState method is normally triggered when the JList height changes.
The only "insane" thing I'm doing here is that my renderer needs to know what the selected index is. This is because the updateLayoutState method doesn't use the selected index in it's height calculations.
Somehow using list.getSelectedIndex() inside getListCellRendererComponent doesn't work well.
**Edit:**
Check also the anser by nevster and kleopatra, they look way smarter, try them first... | Basically, there are two aspects of the problem, both located in the ui delegate
* it fails to configure the renderer to its *real* state when measuring, that is ignores the selection (and focus) completely
* it is notoriously stubborn against being forced to re-calculate the cached cell sizes: it has no public api to do so and only does voluntarily on model changes.
The remedy to fix the first is indeed the renderer: implement to ignore the given selected flag and query the list for the real selection, as outlined by @Andy. In code, using the OP's components
```
ListCellRenderer renderer = new ListCellRenderer() {
Yeah yeah = new Yeah(false);
Oh oh = new Oh();
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
// ignore the given selection index, query the list instead
if (list != null) {
isSelected = list.isSelectedIndex(index);
}
if (isSelected || ((Integer) value) == 42) {
yeah.isSelected = isSelected;
return yeah;
}
return oh;
}
};
list.setCellRenderer(renderer);
```
To fix the second, a custom ui delegate (as suggested in others answers as well) is a possible solution. Though some work in the general case, if supporting multiple LAFs is needed.
A less intrusive but slightly dirty method to force the ui into voluntarily update its cache is to send a fake ListDataEvent on selectionChange:
```
ListSelectionListener l = new ListSelectionListener() {
ListDataEvent fake = new ListDataEvent(list, ListDataEvent.CONTENTS_CHANGED, -1, -1);
@Override
public void valueChanged(ListSelectionEvent e) {
JList list = (JList) e.getSource();
ListDataListener[] listeners = ((AbstractListModel) list.getModel())
.getListDataListeners();
for (ListDataListener l : listeners) {
if (l.getClass().getName().contains("ListUI")) {
l.contentsChanged(fake);
break;
}
}
}
};
list.addListSelectionListener(l);
```
BTW, JXList of the [SwingX](http://swingx.java.net) project has a custom ui delegate - mainly for supporting sorting/filtering - with public api to re-calculate the cache, then the above ListSelectionListener would be simplified (and clean :-) to
```
ListSelectionListener l = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
((JXList) e.getSource()).invalidateCellSizeCache();
}
};
list.addListSelectionListener(l);
``` | Java Swing: JList with ListCellRenderer selected item different height | [
"",
"java",
"swing",
"height",
"jlist",
""
] |
I've seen a lot of URIs that look something like this:
```
www.fakesite.net/stories/1234/man_invents_fire
```
and I was wondering if the /1234/man\_invents\_fire part of the URI are actually directories or if they are GET parameters (or something else). I've noticed that a lot of times the /man\_invents\_fire segment is unnecessary (can be removed with no consequences), which led me to believe that the /1234/ is the id number for the story in a database table (or something along those lines).
If those segments of the URI are GET parameters, is there an easy way of achieving this?
If they aren't, what is being done?
(also, I am aware that CodeIgnitor gives this kind of functionality, but I was curious to find out if it could be easily achieved without CodeIgnitor. I am, however, generally PHP, if that is relevant to an answer)
Thanks | Easiest thing to do is route **everything** into a main index.php file and figure out your routing from there by running $pieces = explode("/", $\_SERVER['REQUEST\_URI']);
After installing/enabling mod\_rewrite, make sure allow override is not set to false in your apache config (to allow .htaccess to be read), then throw this in your docroot's .htaccess file.
```
<ifModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-s #Make sure the file doesn't actually exist (needed for not re-routing things like /images/header.jpg)
RewriteRule . /index.php [L,QSA] #re-route everything into index.php
</IfModule>
``` | That is called url rewriting, google for it, you will find a lot of information about that. | passing GET parameters that look like URI directories | [
"",
"php",
"html",
"apache",
"mod-rewrite",
"uri",
""
] |
I have a single code file for my Google App Engine project. This simple file has one class, and inside it a few methods.
Why does this python method gives an error saying global name not defined?
Erro NameError: global name 'gen\_groups' is not defined
```
import wsgiref.handlers
from google.appengine.ext import webapp
from django.utils import simplejson
class MainHandler(webapp.RequestHandler):
def gen_groups(self, lines):
""" Returns contiguous groups of lines in a file """
group = []
for line in lines:
line = line.strip()
if not line and group:
yield group
group = []
elif line:
group.append(line)
def gen_albums(self, groups):
""" Given groups of lines in an album file, returns albums """
for group in groups:
title = group.pop(0)
songinfo = zip(*[iter(group)]*2)
songs = [dict(title=title,url=url) for title,url in songinfo]
album = dict(title=title, songs=songs)
yield album
def get(self):
input = open('links.txt')
groups = gen_groups(input)
albums = gen_albums(groups)
print simplejson.dumps(list(albums))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
``` | It's an instance method, you need to use `self.gen_groups(...)` and `self.gen_albums(...)`.
**Edit:** I'm guessing the `TypeError` you are getting now is because you removed the 'self' argument from `gen_groups()`. You'll need to put it back in:
```
def get_groups(self, lines):
...
``` | You need to call it explicitly with an instance:
```
groups = self.gen_groups(input)
```
Similarly for some of the other calls you're making in there, e.g. `gen_album`.
Also, see [Knowing When to Use self and `__init__`](http://diveintopython.net/object_oriented_framework/defining_classes.html#d0e11896) for more information. | Why does this python method gives an error saying global name not defined? | [
"",
"python",
"google-app-engine",
""
] |
Is there a .NET equivalent of Java's [`List.subList()`](http://java.sun.com/javase/6/docs/api/java/util/List.html#subList(int,%20int)) that works on `IList<T>`? | using LINQ
```
list.Skip(fromRange).Take(toRange - fromRange)
``` | For the generic `List<T>`, it is the `GetRange(int, int)` method.
Edit: note that this is a shallow copy, not a 'view' on the original. I don't think C# offers that exact functionality.
Edit2: as Kamarey points out, you can have a read-only view:
```
List<int> integers = new List<int>() { 5, 6, 7, 8, 9, 10, 11, 12 };
IEnumerable<int> view = integers.Skip(2).Take(3);
integers[3] = 42;
foreach (int i in view )
// output
```
The above will print 7, 42, 9. | .NET equivalent of Java's List.subList()? | [
"",
"java",
".net",
"list",
"collections",
"sublist",
""
] |
So there are a bunch of questions similar to mine, but none exactly what I need.
I have a combobox that is populated with a list of cities. I turned on the Autocomplete and that works exactly how i want with the suggestappend also turned on. The problem is, though, if the user tries to tab out of the combo box, it does not actually select the item. here is an example:
I am searching for "Orlando". If i type in "orla", the suggestion fills out the rest of the word (selected), so it shows "orlando". So that is the item I want to select. If i hit enter and then tab out, it will select the item and then tab out. What i need though, is for tabbing out to select the underlying item that matches the word.
If i need to explain more, I can.
Thanks in advance!
Luke | Which version of .NET are you using? I tried it in 3.5, and the behavior is the opposite of what you describe. When I type a partial name and tab out, it selects the item in the list. If I hit enter, it doesn't select the item, and it actually clears the value I just entered.
How are your properties set on the ComboBox? I have AutoCompleteMode = SuggestAppend and AutoCompleteSource = ListItems. | I get the same behaviour as OP and the marked answer (from Albert who is unable to reproduce the problem) isn't a solution. This issue has also been reported to Connect as a Bug:
<https://connect.microsoft.com/VisualStudio/feedback/details/711945/tab-on-a-winforms-combobox-with-properties-dropdownstyle-dropdownlist-autocompletemode-append-autocompletesource-listitems-doesnt-work-correctly>
I didn't bother creating a custom combobox control as specified in the workaround section of the Connect Bug. Instead I just **set the dropdownlist with a default value:**
```
cboAccount.SelectedValue = _accountList(0).Key; //<--Here I set a default value
cboAccount.DroppedDown = true;
``` | Combobox Autocomplete Tab-out does not select item | [
"",
"c#",
"combobox",
"autocomplete",
"tabbing",
""
] |
I have a PHP script that connects to an api and posts information to their systems, but when its trying to connect it throws a fatal error:
```
Fatal error: Uncaught exception 'Exception' with message 'Problem with
'http://apitestserver.co.uk:9000/Service.svc/Items' in
/var/www/html/e/connect_test.php:17 Stack trace: #0
/var/www/html/e/connect_test.php(39):
do_http_request('http://apitest....', 'hello') #1 {main} thrown in
/var/www/html/e/connect_test.php on line 17
```
If I send it to a PHP script which just grabs the IP then it works, but if I send it to the API it doesn't. My PHP script creates XML and then forwards to the server. I was getting errors so I just created the following smaller script purely to test the connection:
```
function do_http_request($url, $data, $method = 'POST',
$optional_headers = 'Content-Type: application/atom+xml') {
$params = array(
'http' => array(
'method' => $method,
'content' => $data
)
);
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url");
}
$metaData = stream_get_meta_data($fp);
fclose($fp);
if(!preg_match('~^HTTP.*([0-9]{3})~',
$metaData['wrapper_data'][0], $matches)){
throw new Exception('MALFORED RESPONSE - COULD NOT UNDERSTAND HTTP CODE');
}
if (substr($matches[1], 0, 1) != '2') {
throw new Exception('SERVER REPORTED HTTP ERROR ' . $matches[1]);
}
return $response;
}
$data = 'hello';
$paul =
do_http_request('http://apitestserver.co.uk:9000/Service.svc/Items',$data);
echo $paul;
```
If I change the URL to a simple script on another one of our servers which just grabs the IP of the incoming connection and returns it:
```
$ip=$_SERVER['REMOTE_ADDR'];
echo 'IP equals = ' . $ip;
```
Then it works fine with no errors.
Update -
with errors on it throws the following warning, probably because the script is not sending the correct info to the API
```
Warning: fopen(http://apitestserver.co.uk:9000/Service.svc/Items)
[function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1
500 Data at the root level is invalid. Line 1, position 1.
```
Also note that I can access the api server fine using fiddler to send manually created items across, its just when this script tries to connect and send data there is an issue. I wrote another quick script which connects and prints out the default response (an rss feed of submitted items)
When I run the 'main' connector script it throws the following two errors
```
Warning: fopen() [function.fopen]: php_network_getaddresses:
getaddrinfo failed: Name or service not known in
/var/www/html/e/sequence.php on line 65
Warning: fopen(http://apitestserver.co.uk:9000/Service.svc/Items)
[function.fopen]: failed to open stream: Operation now in progress
in /var/www/html/e/sequence.php on line 65
``` | I would suggest using [curl](https://www.php.net/curl) instead of `fopen()`. curl is both more flexible, and more secure. Many servers disable [allow\_url\_fopen](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen), curl also fails more gracefully when there are problems on the remote server. | I just tested the URL in my browser and got a connection error.
Maybe the problem is with their server (or you have the wrong URL)?
Edit:
Looks like ther server is throwing a 500 error - maybe because the data you're posting is invalid.
You could use a packet sniffer and check the exact data you're sending to the server (or use cURL as suggested by @acrosman) | PHP fatal error: Uncaught exception 'Exception' with message | [
"",
"php",
"error-handling",
""
] |
Catching an exception that would print like this:
```
Traceback (most recent call last):
File "c:/tmp.py", line 1, in <module>
4 / 0
ZeroDivisionError: integer division or modulo by zero
```
I want to format it into:
```
ZeroDivisonError, tmp.py, 1
``` | ```
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
``` | Simplest form that worked for me.
```
import traceback
try:
print(4/0)
except ZeroDivisionError:
print(traceback.format_exc())
```
Output
```
Traceback (most recent call last):
File "/path/to/file.py", line 51, in <module>
print(4/0)
ZeroDivisionError: division by zero
Process finished with exit code 0
``` | When I catch an exception, how do I get the type, file, and line number? | [
"",
"python",
"exception",
"stack-trace",
"traceback",
""
] |
I have an app that needs to do one thing, and one thing only, on a schedule and it will be able to calculate easily the time it next needs to run. It may not need to run this task for days or months from now, but will probably be active in every other respect every few milliseconds.
I'm looking for a simple lightweight approach to scheduling that one task to run. | If your java app is intended to be running continuously then you can use the [Timer](http://java.sun.com/j2se/1.5.0/docs/api/) class to schedule execution
If your app isn't going to be running continuously then the other answers are correct. cron / task scheduler are the way to go. | On Unix, have a look at the system tools `cron` or `at`.
On Windows, there is a job scheduler in the system settings.
For a simple Java-only solution, try the [Timer API](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html).
For a more complex Java-only solution, have a look at [quartz](http://www.quartz-scheduler.org/). | I need to sleep for long periods (days) in Java | [
"",
"java",
"scheduled-tasks",
""
] |
Is it possible to use a dynamic variable (not sure about naming) in C#?
In PHP, I can do
```
$var_1 = "2";
$var_2 = "this is variable 2";
$test = ${"var_".$var_1};
echo $test;
output: this is variable 2;
```
Can we do this in C#? | In C#, you use [dictionaries](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx) to associate values with strings. | No, basically. The compiler doesn't guarantee that method variables will exist (in their form as written), or with names...
If they were fields (instance or static), then you could use reflection to get the values; but not method variables. For what you want, perhaps use a dictionary as a substitute?
```
var vars = new Dictionary<string,object>();
vars["var_1"] = "2";
vars["var_2"] = "this is variable 2";
Console.WriteLine(vars["var_" + vars["var_1"]]);
``` | Dynamic variable in C#? | [
"",
"c#",
"dynamic-variables",
""
] |
Our software currently has many features. I've been asked to make a free trial version which consist of a lightweight version of the full software. Only a few specific features would be available in the trial. And since a jar file isn't encrypted, I was relunctant to release a full version with hardcoded restrictions. I want to be able to have 2 jars : 1 containing the basic features and 1 with the advanced features.
The features are in different menus. It would be nice it the code would try to load the jar with the extra features at start up and display a message (like : this feature is unvailable in the trial) when the non-paying user selects an advanced menu. On the other hand, a paying user with access to the advanced features jar wouldn't know the difference (I'm talking about the difference between now, 1 jar, and the new method, 2 separate jars).
* Any tip on how to proceed ?
* Any warning on common mistakes to avoid ?
* Any better strategy than the separate jars ?
Edit : The best suggestion so far describes how to do my crippleware, but also warns me not to do a crippleware. So what do should I do ? | As you mentioned, you would probably have 2 jars:
1 with the basic features and stubs for the advanced features.
1 with the actual advanced features.
You could use a factory class with a config setting to determine whether to create the stub classes or the real classes - e.g. "FancyFeatureClass" or "FancyFeatureClassStub". "FancyFeatureClassStub" would be included in the "lite" distribution, but "FancyFeatureClass" would only be in the advanced features jar.
If they tried to change the config setting to create the real class without having the jar with the real classes, they would just end up getting class not found errors.
When upgrading, add advanced features jar to the classpath and change the config setting to tell the factory class to create the real classes instead of the stubs. Assuming your app could be split up that way, it should work fine.
As for common mistakes - I think you've already made one - probably not your fault though :)
"Crippleware" is a bad way to evaluate a product. Better to release a full featured version with an expiration or a nag screen than to release a crippled product. Not having those advanced features would probably make it difficult for someone to really evaluate the product. | Many technologies allow pluggable features (called plugins or addons usually).
The idea is that your core code (or framework) declares some interfaces (a well-thought API is ideal). Plugins can provide new implementations of an interface, and register it to the framework.
In its boot sequence, your framework will look (through some convention, in a file for example) if there are plugins, and give them a chance to execute their own boot sequence, consisting of the registration.
After the boot phase, a runtime example (for menus) : The framework looks it the registry where he stores the menus. The registry contains the menus the framework himself declared, plus any additionals provided by plugins... It displays all of them.
If you want specifically the behavior you asked for, I would implement this as follow :
* menus available in all cases are declared and implemented in the framework
* menus available only in the expanded edition are implemented twice :
1. in the framework, the implementation would simply display a message
(like : this feature is unvailable in the trial
2. in the plugin (= paid edition), it would override the previous implementation with the real one, that does the real job.
That way, you paying users have all normal functionality, with the trial version shows the warnings.
Many technologies exist to implement this, the best choice depends on what you already know/use/feel confortable with :
* interface implementation is plain java, a string in the manifest of your plugin jar can mention the class to start.
* Eclipse RCP has full implementation of menus that way (so you would have nothing to code, only configuration)
* Spring is also pretty good when you use interfaces ... | Lite version of a Java software | [
"",
"java",
"plugins",
"add-in",
"packaging",
""
] |
I want to show pound sign and the format 0.00 i.e £45.00, £4.10 . I am using the following statement:
```
<td style="text-align:center"><%# Convert.ToString(Convert.ToSingle(Eval("tourOurPrice")) / Convert.ToInt32(Eval("noOfTickets")), new System.Globalization.CultureInfo("en-GB")) %></td>
```
But it is not working. What is the problem.
Can any one help me??? | Use the [Currency](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx) standard format string along with the [string.Format](http://msdn.microsoft.com/en-us/library/1ksz8yb7.aspx) method that takes a format provider:
```
string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:C}", amount)
```
The CultureInfo can act as a format provider and will also get you the correct currency symbol for the culture.
Your example would then read (spaced for readability):
```
<td style="text-align:center">
<%# string.Format(new System.Globalization.CultureInfo("en-GB"),
"{0:C}",
Convert.ToSingle(Eval("tourOurPrice"))
/ Convert.ToInt32(Eval("noOfTickets")))
%>
</td>
``` | How about
```
<%# (Convert.ToSingle(Eval("tourOurPrice")) / Convert.ToInt32(Eval("noOfTickets"))).ToString("C", New System.Globalization.CultureInfo("en-GB")) %>
``` | Format string by CultureInfo | [
"",
"c#",
"asp.net",
"cultureinfo",
""
] |
**Duplicate of** [What is the purpose/advantage of using yield return iterators in C#?](https://stackoverflow.com/questions/1088442/what-is-the-purpose-advantage-of-using-yield-return-iterators-in-c)
Okay it just not this. Can you explain me in details that how does the two different?
Like Returning an Array (Lets say string)
or doing a yield return with iterator(also string)
I find them to be the same.
Please go into detail. | An array is a pointer to a fixed sized, random-access chunk of data. The caller can update values, access values in any order etc.
An iterator is a key to a **sequence** of values (which could be infinite in length). The caller can only access them in the order supplied by the source, and cannot update them.
There is more overhead accessing each value in a sequence, but it has the advantage of not needing all the data at once, so can be more efficient for mid-to-long sequences. | If you return an iterator that cannot change the internal data structure, you might not need to make a copy of it.
On the other hand, a common mistake is to return something you use internally, and this will allow outside code to modify your internal data structures, which is usually a big no-no.
For instance, consider the following:
```
Int32[] values = otherObj.GetValues();
values[0] = 10;
```
If the GetValues method simply returns an internal array, that second line will now change the first value of that array. | Difference between Iterator and Array in c# | [
"",
"c#",
"arrays",
"iterator",
""
] |
In certain situations I want to add 1 day to the value of my DATETIME formatted variable:
```
$start_date = date('Y-m-d H:i:s', strtotime("{$_GET['start_hours']}:{$_GET['start_minutes']} {$_GET['start_ampm']}"));
```
What is the best way to do this? | If you want to do this in PHP:
```
// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));
```
If you want to add the date in MySQL:
```
-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);
``` | There's more then one way to do this with [DateTime](http://www.php.net/manual/en/class.datetime.php) which was introduced in PHP 5.2. Unlike using `strtotime()` this will account for daylight savings time and leap year.
```
$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.3
$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');
// Available in PHP 5.4
echo (new DateTime('2013-01-29'))->add(new DateInterval('P1D'))->format('Y-m-d H:i:s');
// Available in PHP 5.5
$start = new DateTimeImmutable('2013-01-29');
$datetime = $start->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');
``` | adding 1 day to a DATETIME format value | [
"",
"php",
"mysql",
"date",
"datetime",
""
] |
Hi wondering if perhaps someone could shed some light on the below error. The sql works fine locally but i get the the below error remotely.
SQL query:
```
SELECT COUNT(node.nid),
node.nid AS nid,
node_data_field_update_date.field_update_date_value AS node_data_field_update_date_field_update_date_value
FROM node node
LEFT JOIN content_type_update node_data_field_update_date ON node.vid = node_data_field_update_date.vid
WHERE node.type IN ('update')
ORDER BY node_data_field_update_date_field_update_date_value DESC
```
MySQL said:
> #1140 - Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no
> GROUP columns is illegal if there is
> no GROUP BY clause` | The reason a single column using an [aggregate function](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html) works while the version with columns not using aggregate functions doesn't is because you need to specify a `GROUP BY` clause. Here's what your query should look resemble:
```
SELECT COUNT(n.nid),
n.nid,
ctu.field_update_date_value
FROM NODE n
LEFT JOIN CONTENT_TYPE_UPDATE ctu ON ctu.vid = n.vid
WHERE n.type IN ('update')
GROUP BY n.nid, ctu.field_update_date_value
ORDER BY field_update_date_value DESC
```
I changed out your table aliases for shorter ones - easier to read. Here's the meat of your issue:
```
SELECT n.nid,
COUNT(n.fake_example_column),
ctu.field_update_date_value
...
GROUP BY n.nid, ctu.field_update_date_value
```
I altered the example to use a fake column in order to highlight how the GROUP BY needs to be defined. Any column you reference without wrapping in an aggregate function **should** to be mentioned in the `GROUP BY`. I say *should* because [MySQL is the only db I'm aware of that supports a `GROUP BY` where you can selectively omit columns](http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html) - there are numerous SO questions about why queries work on MySQL but can't be ported without change to other dbs. Apparently in your case, you still need to define at least one. | Your server probably has [ONLY\_FULL\_GROUP\_BY](http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_by) turned on. You can either turn it off or add each of your selected fields to the group by. | MySQL #1140 - Mixing of GROUP columns | [
"",
"sql",
"mysql",
"group-by",
"mysql-error-1140",
""
] |
I know enough about SQL to get my job done but reading different articles I see T-SQL, SQL Server and SQL. Are they all the same? What are the major differences between the three?
I know SQL is an ANSI standard. What about the other two? | SQL is the basic ANSI standard for accessing data in a relational database. When you see "MSSQL" it is referring to Microsoft SQL Server, which is the entire database architecture and not a language. T-SQL is the proprietary form of SQL used by Microsoft SQL Server. It includes special functions like cast, convert, date(), etc. that are not part of the ANSI standard.
You will also see things like plSQL, which is Oracle's version of SQL, and there are others as well (mySQL has its own version, for example, and Microsoft Access uses Jet SQL.)
It is important to note the the ANSI standard for SQL has different releases (for example, 92 or 99, representing the year it was released.). Different database engines will advertise themselves as "mostly ANSI-92" compliant or "fully ANSI-99" compliant, etc, and any exceptions will usually be documented.
So although "SQL is SQL", every engine uses its own "flavor" of it, and you do have to do a little reading on the particular platform before you just dive in.
A further note - the SQL extensions, like T-SQL, are generally considered full-fledged programming languages, complete with looping, if/then, case statements, etc. SQL itself is limited to simply querying and updating data and is not considered a true programming language.
Wikipedia has a decent article for an overview here:
<http://en.wikipedia.org/wiki/SQL> | It depends in what context those terms are being used.
They might mean exactly the same or have a slightly different meaning in some situations.
* [T-SQL](http://en.wikipedia.org/wiki/Transact-SQL) - dialect of SQL language used in Microsoft Sql Server
* [MSSQL](http://en.wikipedia.org/wiki/Microsoft_SQL_Server) - Microsoft SQL Server software
* [SQL](http://en.wikipedia.org/wiki/SQL) - Structured Query Language - depending on the context it might mean the sql language itself, sql database or sql database server of any kind. | What are the differences between T-SQL, SQL Server and SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am trying to lock a "boxed" object in a c# app, is this not possible?
```
class t
{
System.Object t_x = new object();
public t(int p)
{
t_x = p;
}
public void w()
{
lock (t_x)
{
for (int i = 0; i < 4; i++)
{
{
t_x = ((int)t_x) + 1;
Console.WriteLine(t_x);
Thread.Sleep(1000);
}
}
}
}
}
```
In another class I can start 2 threads:
```
Thread b1 = new Thread(new ThreadStart(t1.w));
b1.Start();
Thread b2 = new Thread(new ThreadStart(t1.w));
b2.Start();
```
However the portion is not locked.
When I lock an arbitrary object (i.e. one created and not modified as object a=new object()) it locks well.
Is boxing operation somehow "depromotes" my Object?? | You need to create a separate lock object. The problem is that you re-assign t\_x inside the loop. Assuming thread b1 gets inside the loop before b2 gets to the lock statement, b2 will be allowed inside the lock statement because, by that time, t\_x will be a new object that does not have a lock on it. | No, you can't do this - the lock block is shorthand for the following:
```
try(Monitor.Enter(lockObject))
{
//critical section
}
finally
{
Monitor.Exit(lockObject)
}
```
The [documentation for Monitor.Enter](http://msdn.microsoft.com/en-us/library/de0542zz(VS.71).aspx) states, "Use Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, it is boxed as a separate object, and the thread does not block" | C# threading - Lock Object | [
"",
"c#",
"multithreading",
"locking",
""
] |
I have a large image in a gallery that needs to change when one of the thumbnails is clicked within a unordered list below. The images are coming in dynamically so the jquery script needs to be able to take the src of the thumbnail, remove "-thumb" from the filename, and then replace the large image with the new source.
Please let me know what is my best approach to a gallery like this.
Thanks in advance.
-B | Something like:
```
$('img.thumb').click(function() {
var src = $(this).attr('src');
$('#bigImage').attr('src', src.replace(/-thumb/,''));
});
```
The below examples apply if your thumbs are being loaded in via ajax:
(1) Using [Events/live](http://docs.jquery.com/Events/live):
```
$('img.thumb').live("click", function() {
var src = $(this).attr('src');
$('#bigImage').attr('src', src.replace(/-thumb/,''));
});
```
(2) As a callback to one of jQuery's ajax methods (e.g.):
```
function initThumbs()
{
$('img.thumb').click(function() {
var src = $(this).attr('src');
$('#bigImage').attr('src', src.replace(/-thumb/,''));
});
}
$('#thumbsDiv').load('thumbs.php?p=2', initThumbs);
``` | ```
$().ready(function() {
//get all images from unordered list and apply click function
$('ul#myList img').each(function() {
$(this).click(function() {
$('#mainImage').attr('src', $(this).attr('src').replace('-thumb', ''));
});
});
});
``` | jQuery Image Change - Gallery View | [
"",
"javascript",
"jquery",
"image",
"image-gallery",
""
] |
The following method generates a warning, but it looks safe to me. I'm sure the problem is with me:
```
public <S extends CharSequence> S foo(S s) {
return (S) new StringBuilder(s);
}
```
It looks like this will always return the argument `s`. Can anyone show an example that would cause this method to throw an exception?
**Edit:** I'm not particularly interested in the question of whether generics are necessary here. Rather, I'm looking for a demonstration of how this method is unsafe. | foo("test");
is enough to make java try to cast a StringBuilder in a String.
Your code is guaranteed o be wrong, can you explain what you're trying to achieve plase ? | It's unsafe because while StringBuilder is a CharSequence, it isn't necessarily of type S (in fact, it almost certainly won't be). You can see this failing just by passing a `String` into your method. This will construct a `StringBuilder` using your `String` as an argument, and then try to cast your `StringBuilder` to `String` (which will fail).
There's probably no need to use generics here at all, this should work fine:
```
public CharSequence foo(CharSequence s) {
return new StringBuilder(s);
}
``` | Why is this generic method unsafe? | [
"",
"java",
"generics",
"warnings",
""
] |
There are many ways to handle forms. one is to simply submit the form and the get variables on php and another one that i'm thinking of, is to send data with ajax and during this process we can show a dialog and show the information about processing the data with a progress bar.
despite the fact that ajax is faster than the standard technique and sometimes it's easier to use why there's a very few websites that are using the ajax method ? | Javascript, as a language, should be treated primarily as an 'addon'. Your page should work perfectly without using Javascript, AJAX, or any other browser languages.
What should ideally happen, is when you Javascript loads, it puts in an event catcher that when the form is submitted, it returns false and instead submits it using AJAX. If Javascript is not enabled, nothing every submits false, and the form is submitted server side.
This allows the most compatability, and is the reason people discourage having a lot of Javascript in the actual tags like this:
Go
Some people turn off Javascript, and some old browser might have errors with that onClick event. Heck, people might develop new browsers that omit Javascript completely for one reason or another.
The Point is that Javascript should simply be an 'addon' to the web page, not the heart of it.
(Unless it is a Javascript Application, which does absolutely everything through Javascript. Normal forms however are not Javascript Applications) | It's not that you shouldn't be using ajax to `post` forms, is that you have to "double" your work (for small amounts of double). I usually make a form work with normal submit, and **then** I override it with javascript. That way you have a non-javascript fall-back, and don't leave anyone behind. Also lok at jQuery's [`$.post`](http://docs.jquery.com/Ajax/jQuery.post) and [`$('#myform').serialize`](http://docs.jquery.com/Ajax/serialize) methods.
There is no *intrinsic* reason that it isn't used more. It's just that for most websites, AJAX isn't really needed. | Simple page submit - vs - Ajax loader | [
"",
"php",
"html",
"ajax",
"jquery-ui",
"jquery",
""
] |
> **Possible Duplicate:**
> [HTML table with fixed headers?](https://stackoverflow.com/questions/673153/html-table-with-fixed-headers)
Looking for a solution to create a table with a scrollable body, and a static/fixed header.
Searching around seems to produce *MANY* flaky pieces of code, either not working in IE, requiring a huge amount of Javascript and tweaking, or a silly amount of CSS hacks etc.
To be honest, if it's a case of CSS hacks or Javascript, I think I'd prefer to go the Javascript option.
The alternative I guess is to place it all in a div, and just scroll the entire table - but that's a bit naff :D | ```
<table style="width: 300px" cellpadding="0" cellspacing="0">
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
</table>
<div style="overflow: auto;height: 100px; width: 320px;">
<table style="width: 300px;" cellpadding="0" cellspacing="0">
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
</table>
</div>
```
This creates a fixed column header with the scrollable table below it. The trick is to embed the table you want to scroll in a tag with the overflow attribute set to auto. This will force the browser to display a scrollbar when the contents of the inner table are larger than the height of the surrounding .
The width of the outer must be larger than the width if the inner table to accommodate for the scrollbar. This may be difficult to get exactly right, because some users may have set their scrollbars to be wider or smaller than the default. However, with a difference of around 20 to 30 pixels you'll usually be able to display the scrollbar just fine.
CSS-Tricks also talks about using JavaScript and CSS to help with this as well so you can use highlighting. Here is the link to that [article](http://css-tricks.com/video-screencasts/66-table-styling-2-fixed-header-and-highlighting/). | I've just put together a jQuery plugin that does exactly what you want. Its very small in size and really easy to implement.
All that is required is a table that has a thead and tbody.
You can wrap that table in a DIV with a classname and the table will always resize to fit in that div. so for example if your div scales with the browser window so will the table. The header will be fixed when scrolling. The footer will be fixed (if you enable a footer). You also have the option to clone the header in the footer and have it fixed. Also if you make your browser window too small and all columns can't fit...it will also scroll horizontally (header too).
This plugin allows the browser to size the columns so they aren't fixed width columns.
you just pass the DIV's classname to the plugin like so: $('.myDiv').fixedHeaderTable({footer: true, footerId: 'myFooterId'}); and the plugin will do the rest. FooterID is a element on the page that contains the mark-up for your footer. this is used if you want to have pagination as your footer.
If you have multiple tables on the page it will also work for each table you want to have a fixed header.
check it out here: <http://fixedheadertable.mmalek.com/>
Keep in mind its still 'beta' so I am adding new features and bug fixes daily.
Supported browsers: IE6, IE7, IE8, FireFox, Safari, and Chrome
Here is a link to my response to another person who had the same question: [Frozen table header inside scrollable div](https://stackoverflow.com/questions/486576/frozen-table-header-inside-scrollable-div/1533619#1533619) | Table - fixed header, scrollable body, most robust/simple solution? | [
"",
"javascript",
"html",
"css",
"html-table",
""
] |
I have a Hashtable object which "names" or "map" various fields in a class with a string
```
ref class Interrupt{
Interrupt(){
this->type = 0;
this->size = 0;
}
int type;
int size;
}
Interrupt^ interrupt = gcnew Interrupt();
Hashtable^ map = gcnew Hashtable();
map->Add("InterruptType", interrupt->type);
map->Add("InterruptSize", interrupt->size);
```
this class is modified during runtime so type and size are both equals to 2.
further down the road I query my Hashtable but the values didn't change. I understand that it is because they are immutable. Is there a way I can specify my Hashtable to hold pointers to the fields of my class instead of storing the value of the reference?
I know I can modify class Interrupt to hold custom objects instead of raw int, but it would invole A LOT of refactoring. | > I understand that it is because they are immutable.
You understand wrong. Yes, integers are immutable. But the map values didn't change because integers are value types, and so were passed to the map's Add() method by value. In other words, the map holds a *copy* of the value passed to the Add() method rather than a reference to the *variable* passed to the method.
To fix this, you need to wrap your integers in a reference type (a class) and give the map a reference to the desired instance of that class. Then make sure that whenever you change your integers you're changing them as members of the correct instance. | You could change it to have your Hashtable just hold a reference to your class itself (Interrupt) instead of the individual int values. This way, you could look up the int values based on the instance. | Map pointers to immutable objects with Hashtable in .NET | [
"",
".net",
"c++",
"pointers",
"hashtable",
"immutability",
""
] |
OK, Apologies if this has already been asked and/or Answered but I'm struggling to find the right situation to the problem that I'm investigating as the correct terminology is hard to come by!
I have been tasked into looking for a Roll-Back solution for our deployment if for any reason we have an unsuccessful release. Other than heavily structuring our source control and, if an unsuccessful release occurs, getting the previous version from the SVN and re-publishing to the Live Server is there any better quick solution?
Is there any quick and suitable way to Roll-Back to the previously released version?
I am mainly focussing on Web Services currently as these are front facing and any problems with these could obviously cause a problem to customers and will need to be fixed ASAP.
Please don't hesitate to provide any suggestions and comments as I am eager to hear of any and all ideas.
Thanks in advance! | why don't you just copy the old directory into a backup directory.
if deployment fails, than just copy it back from the backup directory.
should be easily done with a small batch script or maybe nant for better configuration possibillites | I have always created an installer for my WCF services. I can only assume that this would work for ASMX services.
If you haven't created an installer before, there is a learning curve. I only glanced over this: <http://aspalliance.com/622>, but it looked pretty close to what I have done. Let me know what you think. | C# Web Services Deployment Version Roll Back / Removal | [
"",
"c#",
"web-services",
"version-control",
"deployment",
""
] |
I am looking to encrypt data. I want to generate encryption keys based on a password, and some moving value, like time. The goal is to have the key change, but have anyone that knows the password be able to decrypt. This is happening in C#. I am using the following code to hash the password.
```
private static string GetPasswordHash(string password)
{
TimeSpan span = (DateTime.UtcNow - new DateTime(1900, 1, 1));
string result = Convert.ToInt32(span.TotalHours).ToString();
result += password;
result += Convert.ToInt32(span.TotalDays).ToString();
result = Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(result)));
return result;
}
```
I then use that hash, plus a salt to generate a key.
```
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(GetPasswordHash(password), salt);
rdb.IterationCount = 1000;
RijndaelManaged rm = new RijndaelManaged();
rm.KeySize = 256;
rm.Key = rdb.GetBytes(32);
rm.IV = rdb.GetBytes(16);
```
There seem to be issues with the way I am doing this. Some of the computers are in different timezones, or if the hour ticks as I send the data, or if the machines times are slightly off. Are there better suggestions? | The standard strategy is to just send the value (time, etc.) just be sent with the encryption key. Since the value you are using is public knowledge, it is fine if whoever first creates the password provides the "moving value" publicly. See [Salt](http://en.wikipedia.org/wiki/Salt_(cryptography)). What you are doing is not a new technique. You also seem to be using [Key Strengthening](http://en.wikipedia.org/wiki/Key_strengthening). | You might just send the changing part (unencrypted) along with the encrypted data, so that anyone who knows the secret password can easily reconstruct the password used for encryption. Since the changing part is relatively easy to guess, it wouldn't make it much less secure. | How would you generate repeateable encryption key? | [
"",
"c#",
"encryption",
"timezone",
"passwords",
"rijndaelmanaged",
""
] |
I have been trying to make the NLTK (Natural Language Toolkit) work on the Google App Engine. The steps I followed are:
1. Download the installer and run it (a .dmg file, as I am using a Mac).
2. copy the nltk folder out of the python site-packages directory and place it as a sub-folder in my project folder.
3. Create a python module in the folder that contains the nltk sub-folder and add the line: `from nltk.tokenize import *`
Unfortunately, after launching it I get this error (note that this error is raised deep within NLTK and I'm seeing it for my system installation of python as opposed to the one that is in the sub-folder of the GAE project):
```
<type 'exceptions.ImportError'>: No module named nltk
Traceback (most recent call last):
File "/base/data/home/apps/xxxx/1.335654715894946084/main.py", line 13, in <module>
from lingua import reducer
File "/base/data/home/apps/xxxx/1.335654715894946084/lingua/reducer.py", line 11, in <module>
from nltk.tokenizer import *
File "/base/data/home/apps/xxxx/1.335654715894946084/lingua/nltk/__init__.py", line 73, in <module>
from internals import config_java
File "/base/data/home/apps/xxxx/1.335654715894946084/lingua/nltk/internals.py", line 19, in <module>
from nltk import __file__
```
Note: this is how the error looks in the logs when uploaded to GAE. If I run it locally I get the same error (except it seems to originate inside my site-packages instance of NLTK ... so no difference there). And "xxxx" signifies the project name.
So in summary:
* Is what I am trying to do even possible? Will NLTK even run on the App Engine?
* Is there something I missed? That is: copying "nltk" to the GAE project isn't enough?
**EDIT: fixed typo and removed unnecessary step** | The problem here is that `nltk` is attempting to do recursive imports: When `nltk/__init__.py` is imported, it imports `nltk/internals.py`, which then attempts to import `nltk` again. Since `nltk` is in the middle of being imported itself, it fails with a (rather unhelpful) error. Whatever they're doing is pretty weird anyway - it's unsurprising something like `from nltk import __file__` breaks.
This looks like a problem with nltk itself - does it work when imported directly from a Python console? If so, they must be doing some sort of trickery in the installed version. I'd suggest asking on the nltk groups what they're up to and how to work around it. | [oakmad](http://groups.google.com/group/nltk-users/browse_thread/thread/95db3032ccca7ab8/) has managed to successfully work through
deploying **SEVERAL** NLTK modules to GAE. Hope this helps.
But , but be honest, I still don't think it's true even after read the post. | Using the Python NLTK (2.0b5) on the Google App Engine | [
"",
"python",
"google-app-engine",
"nlp",
"nltk",
""
] |
I have a watermark script I am working on, the results are good on PNG and on JPG images however a gif image, not so good. I am using PHP and GD
Below you can see the difference in quality of the watermark.
Anyone know how to improve this?
For the gif version I am using
```
$image = imagecreatefromgif($source_file);
imagecopymerge($image, $watermark, $x, $y, 0, 0, $water_width, $water_height, 65);
imagegif($image, $source_file);
```
gif image = bad quality
[gif image http://img2.pict.com/fd/46/00/1471179/0/gif.gif](http://img2.pict.com/fd/46/00/1471179/0/gif.gif)
jpg image = good
[jpg image http://img2.pict.com/82/a1/5a/1471181/0/jpg.jpg](http://img2.pict.com/82/a1/5a/1471181/0/jpg.jpg) | GIF images have a fixed palette that can contain a maximum of 256 colors. The issue here is probably that the image your inserting uses colors that isn't available in the target image.
I have never tried this, but it might be worth a shot. You could try converting the gif image to a true color image first, then do the watermarking and after that converting it back to gif.
```
$image = imagecreatefromgif($source_file);
// create a true color image of the same size
$image2 = imagecreatetruecolor(imagesx($image), imagesy($image));
// copy the original gif image on to the true color image
imagecopy($image2, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
// copy the watermark onto the new true color image
imagecopymerge($image2, $watermark, $x, $y, 0, 0, $water_width, $water_height, 65);
// write the new image to disk
imagegif($image2, $source_file);
```
Try it and see if it makes a difference.
There's also a couple of palette manipulation functions available that might help:
1. [imagecolormatch()](https://www.php.net/manual/en/function.imagecolormatch.php)
2. [imagetruecolortopalette()](https://www.php.net/manual/en/function.imagetruecolortopalette.php)
3. [imagepalettecopy()](https://www.php.net/manual/en/function.imagepalettecopy.php)
I'm not sure how you would apply them, but I'm guessing that there's a few things you could do to improve the results. | GIF only supports a color palette of 256 colors. Therefore, the colors of your watermark image have to be mapped to this palette. This caused them to be rendered and saved with different colors than before. Due to this small palette, GIF is not recommended for photos in general, anyways. | Bad quality of GIF image in PHP GD | [
"",
"php",
"gd",
""
] |
I think the problem is pretty common. You have some input string, and have to call a function depending on the content of the string. Something like a switch() for strings.
Think of command line options.
Currently I am using:
```
using std::string;
void Myclass::dispatch(string cmd, string args) {
if (cmd == "foo")
cmd_foo(args);
else if (cmd == "bar")
cmd_bar(args);
else if ...
...
else
cmd_default(args);
}
void Myclass::cmd_foo(string args) {
...
}
void Myclass::cmd_bar(string args) {
...
}
```
and in the header
```
class Myclass {
void cmd_bar(string args);
void cmd_foo(string args);
}
```
So every foo and bar I have to repeat four (4!) times. I know I can feed the function pointers and strings to an static array before and do the dispatching in a loop, saving some if...else lines. But is there some macro trickery (or preprocessor abuse, depending on the POV), which makes is possible to somehow define the function and at the same time have it update the array automagically?
So I would have to write it only twice, or possibly once if used inline?
I am looking for a solution in C or C++. | The ugly macro solution, which you kind-of asked for. Note that it doesn't automatically register, but it does keep some things synchronized, and also will cause compile errors if you only add to mappings, and not the function in the source file.
Mappings.h:
```
// Note: no fileguard
// The first is the text string of the command,
// the second is the function to be called,
// the third is the description.
UGLY_SUCKER( "foo", cmd_foo, "Utilize foo." );
UGLY_SUCKER( "bar", cmd_bar, "Turn on bar." );
```
Parser.h:
```
class Myclass {
...
protected:
// The command functions
#define UGLY_SUCKER( a, b, c ) void b( args )
#include Mappings.h
#undef UGLY_SUCKER
};
```
Parser.cpp:
```
void Myclass::dispatch(string cmd, string args) {
if (cmd == "")
// handle empty case
#define UGLY_SUCKER( a, b, c ) else if (cmd == a) b( args )
#include Mappings.h
#undef UGLY_SUCKER
else
cmd_default(args);
}
void Myclass::printOptions() {
#define UGLY_SUCKER( a, b, c ) std::cout << a << \t << c << std::endl
#include Mappings.h
#undef UGLY_SUCKER
}
void Myclass::cmd_foo(string args) {
...
}
``` | It sounds like you're looking for the [Command pattern](http://en.wikipedia.org/wiki/Command_pattern)
Something like this:
Create a map like this
```
std::map<std::string, Command*> myMap;
```
then just use your key to execute the command like this....
```
std::map<std::string, Command*>::iterator it = myMap.find(str);
if( it != myMap.end() ) {
it->second->execute()
}
```
To register your commands you just do this
```
myMap["foo"] = new CommandFoo("someArgument");
myMap["bar"] = new CommandBar("anotherArgument");
``` | Looking for the most elegant code dispatcher | [
"",
"c++",
"c",
"design-patterns",
"coding-style",
""
] |
We have an ASP.Net application hosted on our network and exposed to a specific client. This client wants to be able to import data from their own server into our application. The data is retrieved with an HTTP request and is CSV formatted. The problem is that they do not want to expose their server to our network and are requesting the import to be done on the client side (all clients are from the same network as their server).
So, what needs to be done is:
1. They request an import page from our server
2. The client script on the page issues a request to their server to get CSV formatted data
3. The data is sent back to our application
This is not a challenge when both servers are on the same domain: a simple hidden iframe or something similar will do the trick, but here what I'm getting is a cross-domain "access denied" error. They also refuse to change the data format to return JSON or XML formatted data.
What I tried and learned so far is:
1. Hidden iframe -- "access denied"
2. XMLHttpRequest -- behaviour depends on the browser security settings: may work, may work while nagging a user with security warnings, or may not work at all
3. Dynamic script tags -- would have worked if they could have returned data in JSON format
4. IE client data binding -- the same "access denied" error
Is there anything else I can try before giving up and saying that it will not be possible without exposing their server to our application, changing their data format or changing their browser security settings? (DNS trick is not an option, by the way). | It might be too late for your client, but since you have have control over both domains, you can try [EasyXDM](http://easyxdm.net/). It's a library which wraps cross-browser quirks and provides an easy-to-use API for communicating in client script between different domains using the best available mechanism for that browser (e.g. [postMessage](https://developer.mozilla.org/en/DOM/window.postMessage) if available, other mechanisms if not).
Caveat: you need to have control over both domains in order to make it work (where "control" means you can place static files on both of them). But you don't need any server-side code changes. | [JSONP](http://ajaxian.com/archives/jsonp-json-with-padding) might be the answer for you if they can server data in a JSON format. Other than that you will always run into [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) issues with cross-domain calls. Have you looked into doing Server-side calls to do HTTP requests to their server? | Cross-domain data access in JavaScript | [
"",
"javascript",
"security",
"cross-domain",
""
] |
I get the error "Not implemented".
I want to compress a file using [7-Zip](http://en.wikipedia.org/wiki/7-Zip) via stdin then take the data via stdout and do more conversions with my application. In the [man page](http://pwet.fr/man/linux/commandes/7z) it shows this example:
[% echo foo | 7z a dummy -tgzip -si -so > /dev/null](http://pwet.fr/man/linux/commandes/7z)
I am using Windows and C#.
Results:
```
7-Zip 4.65 Copyright (c) 1999-2009 Igor Pavlov 2009-02-03
Creating archive StdOut
System error:
Not implemented
```
Code:
```
public static byte[] a7zipBuf(byte[] b)
{
string line;
var p = new Process();
line = string.Format("a dummy -t7z -si -so ");
p.StartInfo.Arguments = line;
p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.BaseStream.Write(b, 0, b.Length);
p.StandardInput.Close();
Console.Write(p.StandardError.ReadToEnd());
//Console.Write(p.StandardOutput.ReadToEnd());
return p.StandardOutput.BaseStream.ReadFully();
}
```
Is there another simple way to read the file into memory?
Right now I can 1) write to a temporary file and read (easy and can copy/paste some code) 2) use a file pipe (medium? I have never done it) 3) Something else. | You might want to try out something like SevenZipSharp <http://www.codeplex.com/sevenzipsharp>, I've never used it personally but it provides a wrapper to the 7za.dll COM library which may be helpful to you.
I've written utilities that utilise 7-Zip via a process myself and haven't had issues though I've never tried to do StdIn and StdOut stuff. In the Help files I have with my version of 7-Zip the page on the -si switch states:
> Note: The current version of 7-Zip does not support reading of archives from stdin.
Note sure if this might be the source of your problem, with specifying both switches it might be confusing 7-Zip.
The examples they show in the help seem to show that -so is used to redirect the output to standard out but requires normal file based inputs to do so. | Here's some info from Igor Pavlov (7z's author), in a thread about ["7zip as a drop-in replacement for gzip/bzip2?"](https://sourceforge.net/p/sevenzip/discussion/45797/thread/f3720dde/)
The suggestion was to basically use 7z as an `xz` surrogate. Just using `xz` should work, but it may not be multi-threaded (and 7z may be).
While attempting to use 7z as in:
```
somecommand | 7zr a -si -so | nc -q 2 1.2.3.4 5678
```
[Igor Pavlov says](https://sourceforge.net/p/sevenzip/discussion/45797/thread/f3720dde/#85d3):
> 7z a a.7z -so
> and
> 7z e a.7z -si
> can not be implemeted. since .7z format requires
> "Seek" operation.
>
> Use xz format instead:
> 7z a a.xz file
> it must support all modes.
[And](https://sourceforge.net/p/sevenzip/discussion/45797/thread/f3720dde/#56b6)
> 7-Zip thinks that it needs archive name.
> So you can specify some
> archive name like a.xz
> or
> specify -an switch.
The eventual solution was:
```
cat foo.txt | 7za a -an -txz -bd -si -so | dd of=foo.xz
```
---
[A bug report](https://sourceforge.net/p/sevenzip/bugs/1312/) suggests this should be in the help:
> The current version of 7-Zip support reading of archives from stdin only for xz, lzma, tar, gzip and bzip2 archives, and adding files from stdin only for 7z, xz, gzip and bzip2 archives. | Not able to use 7-Zip to compress stdin and output with stdout? | [
"",
"c#",
"stdout",
"stdin",
"7zip",
""
] |
Is there a CMS that can manage content on a site without having to implement a template?
I've already designed a site with XHTML and CSS, so don't need a template, but do need active content management in static places, such as articles on the homepage and on a couple of other pages.
Preferably open-source all the way, and tableless layout. | I've seen WordPress's backend used as a CMS without a front end template. They used WordPress to write, organize, and otherwise manage content, but used their existing site plus a few database queries to pull in the content from WP.
It may be easier to just create a basic WordPress template from your existing site's design. It takes about 10 minutes when you've done it a lot, or a few hours for a newbie. | You'll need to add the active content parts to your designed site. That means you are creating a template.
A solution could be wordpress. It allows to add small dynamic parts to your site and has a relatively low learning curve. It's open source too. | CMS without a template? | [
"",
"php",
"content-management-system",
""
] |
Under what circumstances would
```
$array[$index] = $element;
```
and
```
unset($array[$index]);
$array[$index] = $element;
```
be different?
Assuming I am not using any references in my array, are these logically equivalent? | If $index isn't numeric second variant would always append element to the end of array, so the order of keys will be changed. | ```
unset($array[$index]);
```
would raise an E\_NOTICE if $index is not found within $array. Other than that it looks the same. | Why would setting an element in an array and unsetting then setting an element in an array be different? PHP | [
"",
"php",
"arrays",
"reference",
""
] |
I already put the log4jConfigLocation in web.xml, but I still get the following warning:
```
log4j:WARN No appenders could be found for logger ⤦
⤥ (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
```
What did I miss?
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>suara2</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>suara2</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
``` | If that's the entire log4j.properties file it looks like you're never actually creating a logger. You need a line like:
```
log4j.rootLogger=debug,A1
``` | I had log4j.properties in the correct place in the classpath and still got this warning with anything that used it directly. Code using log4j through commons-logging seemed to be fine for some reason.
If you have:
```
log4j.rootLogger=WARN
```
Change it to:
```
log4j.rootLogger=WARN, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%5p [%t] (%F:%L) - %m%n
```
According to <http://logging.apache.org/log4j/1.2/manual.html>:
> The root logger is anonymous but can be accessed with the Logger.getRootLogger() method. There is no default appender attached to root.
What this means is that you need to specify some appender, any appender, to the root logger to get logging to happen.
Adding that **console** appender to the rootLogger gets this complaint to disappear. | log4j:WARN No appenders could be found for logger in web.xml | [
"",
"java",
"spring",
"spring-mvc",
"log4j",
""
] |
This is a very low-level, conceptual question.
I have a content site where the users can rate comments left by other users using a dropdown form with two choices, +1 or -1.
I'd like to "transform" this into a nice-looking up/down arrow, a la reddit comments.
I understand that there's a way to do this through CSS + javascript, but I don't understand what that method is and how it works so I can begin looking into it. What exactly so I need to do to turn this dropdown into an up/down voting widget?
I don't need help with the actual ranking of the comments, the algo for it or anything, I just want to understand how to replace this UI element with something more friendly. | The basic technique is to use javascript to hide the actual form element (probably via setting a style of `display:none`) and then add your widget via the DOM manipulation methods. Then, set onclicks on the up/down arrows to update the the value of the hidden form element, increasing/decreasing it by one each time. | You have to have two images for this. And when it is clicked better make an **ajax request** and update the value to database.
If the rating is only for a single time then you can disable the images after successfully updating database.
In SO they are using four images for upvote and downvote. Two of them are indicating the clicked status and two of them for default status. When you click on an image with default status a call is made to server and if it succeeds then the image is changed to an active one. | Basic concept for how javascript replaces an html input with something interactive? | [
"",
"javascript",
"css",
"comments",
""
] |
Consider this division in Python 3:
```
>>> 2/2
1.0
```
Is this intended? I strongly remember earlier versions returning `int/int = int`. What should I do? Is there a new division operator or must I always cast?
---
In 2.x, the behaviour was indeed reversed; see [How can I force division to be floating point? Division keeps rounding down to 0?](https://stackoverflow.com/questions/1267869) for the opposite, 2.x-specific problem. | Take a look at [PEP-238](http://www.python.org/dev/peps/pep-0238/): Changing the Division Operator
> The // operator will be available to request floor division unambiguously. | Oops, immediately found `2//2`. This will output an int rather than a float. | Why does integer division yield a float instead of another integer? | [
"",
"python",
"integer",
"python-3.x",
"division",
""
] |
I have a file (an xml), that is accessed in my code, I would like it to be some how added to the executable, so my utility can access it at runtime, but still be all in one file. Is there a way to doing that? (C#)
Thanks. | Look at [embedded resources](http://www.codeproject.com/KB/dotnet/embeddedresources.aspx) (first result from a Google search, but looks good at first glance)
---
Actually [this article](http://blog.nineon.com/chintan/post/Adding-Using-Embedded-Resources-in-Net-Windows-Application-Class-Library-C-VB-Net-ASP-Net-.aspx) has the advantage of actually telling you how to make something an embedded resource. Between the two of them you should be able to sort out your problem. | Add it as an embedded resource (set the build action for the file to be "Embedded Resource") and use [Assembly.GetManifestResourceStream](http://GetManifestResourceStream) to access it.
Be aware that when accessing a resource stream the name is case sensitive. | Adding a file to a project, that will be added to the exe, and be accessable at runtime | [
"",
"c#",
""
] |
I have a `List<T>` and I need to avoid the behavior I'm about to outline:
```
// assume cls and numberToAdd are parameters passed in.
int pos = numberToAdd;
List<MyClass> objs = new List<MyClass>(numberToAdd);
for(int i = 0; i < numberToAdd; i++)
{
objs.Add(cls);
objs[i].X = -((pos * cls.Width) + cls.Width / 2);
pos--;
}
Console.WriteLine(objs[0].X + "\r\n" + objs[1].X);
```
This results in this writeline printing the same value.
Basically what I need is to change the behavior of the "Add" method. I'd like to add a new instance of the object with the same values and not simply a reference to the same object. I understand this will use alot more memory. | What is the 'cls' variable? Just create a new one inside each loop. What you want to do is clone it; but honestly that'll be confusing. I'd suggest just creating a new one per loop.
-- Edit
Noticed you'd comment about 'cls'.
I suggest you clone it then (assuming you can't change the call and do my above suggestion). Do this by just creating a new one, and copying all the properties over.
Typically, if you have control of the Type of 'cls', you just make a 'Copy' constructor. It's like so:
```
class Foo {
private int x;
public Foo (Foo toCopy) {
this.x = toCopy.x;
}
...
}
``` | Might want to extend cls to include a clone method. Extension method would work if you can't modify the cls class.
then change
objs.Add(cls);
to
objs.Add(cls.Clone()); | .NET Generic List<T> Problem, works by design, need work around. Add value instead of reference | [
"",
"c#",
".net",
"generics",
"generic-programming",
""
] |
I know that converting a pointer to **one** int is unsafe, because the pointer can be bigger than the int in some architectures (for instance in x86\_64).
But what about converting the pointer to several ints, an array of them? If the pointer size is 2 times bigger than int then convert `pointer*` to `int[2]`.
The number of needed ints then is `ceil(sizeof(pointer*)/sizeof(int))`.
I need to do this because there is a function which takes ints as arguments and I want to pass a pointer to it. | **Yet another solution:**
```
#define BIG_ENOUGH 4
typedef union {
int buffer[BIG_ENOUGH];
pointer_t* pointer;
} proxy_t;
static_assert(sizeof(pointer_t*) <= BIG_ENOUGH*sizeof(int));
// before calling the function
proxy_t proxy;
proxy.pointer = the_pointer;
// call to the function, cannot be generic here
f(proxy.buffer[0], proxy.buffer[1], proxy.buffer[2], proxy.buffer[3]);
// how to recover the value of the pointer
void f(int b0, int b1, int b2, int b3) {
proxy_t proxy = { { b0, b1, b2, b3 } };
the_pointer = proxy.pointer;
}
``` | Doesn't your platform provide a intptr\_t ? | How to serialize a pointer into an array of ints? | [
"",
"c++",
"c",
"pointers",
"casting",
"portability",
""
] |
I'm working with 2 related tables in a Microsoft SQL Server 2008 environment which are connected via a GUID. In one table, the field has the type `varchar(50)`, the other one is properly types as `uniqueidentifier`. This is obviously bad but I can't change this now because it's given by a legacy piece of software.
The conversion SQL Server needs to perform at each inner join makes queries running terribly slow, since I can't use indices at all. I tried adding a Computed Column, which is persisted, to get the ID stored as a `uniqueidentifer`. This way I could add an index to get it running much faster probably. I failed.
Does anybody know if I can store an explicitly converted value in a computer column. If I can, what's the formula to use here?
Cheers,
Matthias | This worked for me:
```
CREATE TABLE t_uuid (charid VARCHAR(50) NOT NULL, uuid AS CAST(charid AS UNIQUEIDENTIFIER))
CREATE INDEX IX_uuid_uuid ON t_uuid (uuid)
INSERT
INTO t_uuid (charid)
VALUES (NEWID())
SELECT *
FROM t_uuid
``` | CONVERT(uniqueidentifier, your\_varchar\_here) | Type Conversion in Persisted Computed Column | [
"",
"sql",
"sql-server",
"performance",
"indexing",
"calculated-columns",
""
] |
Is there a good library for functional programming in Java?
I'm looking for stuff like [Predicate](http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx) and [List.Find()](http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx) (as a static method). Not complicated to implement, but it would be nice to find a reusable library here. | [FunctionalJava](http://functionaljava.org/) is the best known library; it makes use of Java closures ([BGGA](http://javac.info)) for examples:
```
final Array<Integer> a = array(1, 2, 3);
final Array<Integer> b = a.map({int i => i + 42});
arrayShow(intShow).println(b); // {43,44,45}
```
**EDIT**
Check also [lambdaj](http://code.google.com/p/lambdaj/).
**Further EDIT**
BGGA is entirely optional. It just makes for nicer syntax. | [**Scala**](http://www.scala-lang.org/) is a functional programming language that is fully compatible with Java (runs through the JVM). It offers a beautiful mix of object-oriented and functional techniques along with many improvements over Java in generics and concurrency. [Some even say it could replace Java.](https://stackoverflow.com/questions/1995953/scala-the-java-of-the-future) | Functional Programming in Java | [
"",
"java",
"functional-programming",
""
] |
I'm using eclipse to build an ear file using ant. I'm using oc4j, and I want to make sure that orion-application.xml is included in the build. What I'm currently using but does not work is:
```
<target name="ear" depends="">
<echo>Building the ear file</echo>
<copy todir="${build.dir}/META-INF">
<fileset dir="${conf.dir}" includes="orion-application.xml"/>
</copy>
<ear destfile="${dist.dir}/${ant.project.name}.ear"
appxml="${conf.dir}/application.xml">
<fileset dir="${dist.dir}" includes="*.jar,*.war"/>
</ear>
</target>
```
What is the right way to add this to the ear? | [Ant EAR task](http://ant.apache.org/manual/Tasks/ear.html)
Everything that should go into `META-INF` folder should be specified via nested `<metainf>` fileset:
```
<ear destfile="${dist.dir}/${ant.project.name}.ear"
appxml="${conf.dir}/application.xml">
<metainf dir="${build.dir/META-INF}"/>
<fileset dir="${dist.dir}" includes="*.jar,*.war"/>
</ear>
``` | Try this code:
```
<ear destfile="deploy/iapp.ear"
appxml="workspace/appEAR/EarContent/META-INF/application.xml">
<fileset file="workspace/appEJB/appEJB.jar" />
<fileset file="workspace/appWAR/appWAR.war" />
<zipfileset file="workspace/appLIB/appLIB.jar"
prefix="APP-INF/lib" />
<zipfileset dir="lib/fop" includes="*.jar" prefix="APP-INF/lib" />
<zipfileset dir="lib/poi" includes="*.jar" prefix="APP-INF/lib" />
<zipfileset dir="lib/gxt" includes="*.jar" prefix="APP-INF/lib" />
<metainf dir="workspace/appEAR/EarContent/META-INF">
<exclude name="**/application.xml" />
<exclude name="**/MANIFEST.MF" />
</metainf>
<manifest>
<attribute name="Weblogic-Application-Version"
value="${deploy.revision}" />
</manifest>
</ear>
``` | How do I create an EAR file with an ant build including certain files? | [
"",
"java",
"ant",
"jakarta-ee",
"oc4j",
"ear",
""
] |
How can I combine these 2 array?
```
$array1 = array("gif" => "gif", "jpg" => "jpeg", "jpeg" => "jpeg", "png" =>"png");
$array2 = array("gif" => "0", "jpg" => "90", "jpeg" => "90", "png" => "8");
```
I tried
```
$array1 = array("gif" => "gif" => "0", "jpg" => "jpeg" => "90", "jpeg" => "jpeg" => "90", "png" =>"png" => "8");
```
But of course it didn't work so any help? | This seems to make more sense:
```
$arr = array("gif" => array("extension" => "gif", "size" => "90"),
"jpg" => array("extension" => "jpeg", "size" => "120")
...
);
echo "Extension: " . $arr['gif']['extension'] . " Size or whatever: " . $arr['gif']['size'];
```
To loop over it:
```
foreach($arr as $key => $val) {
echo "Image Type: $key, Extension: " . $val['extension'] . ", Size: " . $val['size'];
}
``` | You have two values for each key. Create a sub-array for each key with more than one value:
```
$ar1 = array( 'key' => array('key1','key2') );
``` | Combine 2 php arrays? | [
"",
"php",
"arrays",
""
] |
Along the lines of my previous question, [How do I convert unicode characters to floats in Python?](https://stackoverflow.com/questions/1263796/how-do-i-convert-unicode-characters-to-floats-in-python) , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.
For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2
I know that I can iterate through the string by character, check for unicodedata.category(x) == "No" on each character, and convert the unicode characters by unicodedata.numeric(x). I would then have to split the string and sum the values. However, this seems rather hacky and unstable. Is there a more elegant solution for this in Python? | I think this is what you want...
```
import unicodedata
def eval_unicode(s):
#sum all the unicode fractions
u = sum(map(unicodedata.numeric, filter(lambda x: unicodedata.category(x)=="No",s)))
#eval the regular digits (with optional dot) as a float, or default to 0
n = float("".join(filter(lambda x:x.isdigit() or x==".", s)) or 0)
return n+u
```
or the "comprehensive" solution, for those who prefer that style:
```
import unicodedata
def eval_unicode(s):
#sum all the unicode fractions
u = sum(unicodedata.numeric(i) for i in s if unicodedata.category(i)=="No")
#eval the regular digits (with optional dot) as a float, or default to 0
n = float("".join(i for i in s if i.isdigit() or i==".") or 0)
return n+u
```
But beware, there are many unicode values that seem to not have a numeric value assigned in python (for example ⅜⅝ don't work... or maybe is just a matter with my keyboard xD).
Another note on the implementation: it's "too robust", it will work even will malformed numbers like "123½3 ½" and will eval it to 1234.0... but it won't work if there are more than one dots. | ```
>>> import unicodedata
>>> b = '10 ⅕'
>>> int(b[:-1]) + unicodedata.numeric(b[-1])
10.2
define convert_dubious_strings(s):
try:
return int(s)
except UnicodeEncodeError:
return int(b[:-1]) + unicodedata.numeric(b[-1])
```
and if it might have no integer part than another try-except sub-block needs to be added. | How do I calculate the numeric value of a string with unicode components in python? | [
"",
"python",
"string",
"unicode",
"floating-point",
""
] |
I have create windows application that routine download file from load balance server, currently the speed is about 30MB/second. However I try to use FastCopy or TeraCopy it can copy at about 100MB/second. I want to know how to improve my copy speed to make it can copy file faster than currently. | One common mistake when using streams is to copy a byte at a time, or to use a small buffer. Most of the time it takes to write data to disk is spent seeking, so using a larger buffer will reduce your average seek time per byte.
Operating systems write files to disk in clusters. This means that when you write a single byte to disk Windows will actually write a block between 512 bytes and 64 kb in size. You can get much better disk performance by using a buffer that is an integer multiple of 64kb.
Additionally, you can get a boost from using a buffer that is a multiple of your CPUs underlying memory page size. For x86/x64 machines this can be set to either 4kb or 4mb.
So you want to use an integer multiple of 4mb.
Additionally if you use asynchronous IO you can fully take advantage of the large buffer size.
```
class Downloader
{
const int size = 4096 * 1024;
ManualResetEvent done = new ManualResetEvent(false);
Socket socket;
Stream stream;
void InternalWrite(IAsyncResult ar)
{
var read = socket.EndReceive(ar);
if (read == size)
InternalRead();
stream.Write((byte[])ar.AsyncState, 0, read);
if (read != size)
done.Set();
}
void InternalRead()
{
var buffer = new byte[size];
socket.BeginReceive(buffer, 0, size, System.Net.Sockets.SocketFlags.None, InternalWrite, buffer);
}
public bool Save(Socket socket, Stream stream)
{
this.socket = socket;
this.stream = stream;
InternalRead();
return done.WaitOne();
}
}
bool Save(System.Net.Sockets.Socket socket, string filename)
{
using (var stream = File.OpenWrite(filename))
{
var downloader = new Downloader();
return downloader.Save(socket, stream);
}
}
``` | Possibly your application can do multi-threading to get the file using multiple threads, however the bandwidth is limited to the speed of the devices that transfer the content | How to make my application copy file faster | [
"",
"c#",
"file-io",
""
] |
This is a problem I have come across a number of times and I'm sure there's an elegant solution I'm missing.
I have some DateTime variables in c# that I get sent from various SQL tables/websites/web services, often sent as strings. The problem is that some of these sources are set up as English (United States) and some are set up as English (British). I don't have control over some of these, as I would dearly like to set them all to one culture or the other.
Until now I have been converting these using a CultureInfo object to format it correctly like:
```
CultureInfo ci = new CultureInfo("en-GB");
Convert.ToDateTime(inputDateTimeString, ci);
```
However, it has only recently occured to me that the conversion doesn't know what culture the original DateTime is in (as I said, it could be either American or British) since it is just a string.
In the case of a date string, say "06/15/2009", this is fine because the conversion recognises that '15' can't be the month. However a date string of "06/07/2009" will always be valid but, depending on whether the original was American or British, it could be referring to different days and months.
Is there a better accepted method for handling DateTime's in general that cuts down on these ambiguities? Thanks.
EDIT:
Right, so it seems there is no reliable way to always convert into the correct format because my information is limited.
One source of these DateTime strings is a .dll I have no control over. However, I DO have control over the SQL login that this .dll uses to access the database where the information is stored. If I were to change the language setting of this login to British English (it is currently American English), would it retrieve DateTime's in that format, or would it have no effect? I'd have to check ofcourse that it didn't screw anything else up, but might it work? | You need to tackle the problem at its source: you're being given data in an ambiguous format. If you can't change the data sources themselves, you should decorate them with a format string or something like that, so that you know to treat the whole data source in one way or the other.
Without that information you simply *can't* reliably parse the data. | What I usually do (with any parsing) is:
1. TryParse using the culture of the user
2. If it fails, Parse using the culture invariant flag | C# date formatting | [
"",
"c#",
"datetime",
""
] |
I need to validate some user input that is encoded in UTF-8. Many have recommended using the following code:
```
preg_match('/\A(
[\x09\x0A\x0D\x20-\x7E]
| [\xC2-\xDF][\x80-\xBF]
| \xE0[\xA0-\xBF][\x80-\xBF]
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
| \xED[\x80-\x9F][\x80-\xBF]
| \xF0[\x90-\xBF][\x80-\xBF]{2}
| [\xF1-\xF3][\x80-\xBF]{3}
| \xF4[\x80-\x8F][\x80-\xBF]{2}
)*\z/x', $string);
```
It's a regular expression taken from <http://www.w3.org/International/questions/qa-forms-utf-8> . Everything was ok until I discovered a bug in PHP that seems to have been around at least since 2006. Preg\_match() causes a seg fault if the $string is too long. There doesn't seem to be any workaround. You can view the bug submission here: <http://bugs.php.net/bug.php?id=36463>
Now, to avoid using preg\_match I've created a function that does the exact same thing as the regular expression above. I don't know if this question is appropriate here at Stack Overflow, but I would like to know if the function I've made is correct. Here it is:
***EDIT [13.01.2010]:***
If anyone is interested, there were several bugs in the previous version I've posted. Below is the final version of my function.
```
function check_UTF8_string(&$string) {
$len = mb_strlen($string, "ISO-8859-1");
$ok = 1;
for ($i = 0; $i < $len; $i++) {
$o = ord(mb_substr($string, $i, 1, "ISO-8859-1"));
if ($o == 9 || $o == 10 || $o == 13 || ($o >= 32 && $o <= 126)) {
}
elseif ($o >= 194 && $o <= 223) {
$i++;
$o2 = ord(mb_substr($string, $i, 1, "ISO-8859-1"));
if (!($o2 >= 128 && $o2 <= 191)) {
$ok = 0;
break;
}
}
elseif ($o == 224) {
$o2 = ord(mb_substr($string, $i + 1, 1, "ISO-8859-1"));
$o3 = ord(mb_substr($string, $i + 2, 1, "ISO-8859-1"));
$i += 2;
if (!($o2 >= 160 && $o2 <= 191) || !($o3 >= 128 && $o3 <= 191)) {
$ok = 0;
break;
}
}
elseif (($o >= 225 && $o <= 236) || $o == 238 || $o == 239) {
$o2 = ord(mb_substr($string, $i + 1, 1, "ISO-8859-1"));
$o3 = ord(mb_substr($string, $i + 2, 1, "ISO-8859-1"));
$i += 2;
if (!($o2 >= 128 && $o2 <= 191) || !($o3 >= 128 && $o3 <= 191)) {
$ok = 0;
break;
}
}
elseif ($o == 237) {
$o2 = ord(mb_substr($string, $i + 1, 1, "ISO-8859-1"));
$o3 = ord(mb_substr($string, $i + 2, 1, "ISO-8859-1"));
$i += 2;
if (!($o2 >= 128 && $o2 <= 159) || !($o3 >= 128 && $o3 <= 191)) {
$ok = 0;
break;
}
}
elseif ($o == 240) {
$o2 = ord(mb_substr($string, $i + 1, 1, "ISO-8859-1"));
$o3 = ord(mb_substr($string, $i + 2, 1, "ISO-8859-1"));
$o4 = ord(mb_substr($string, $i + 3, 1, "ISO-8859-1"));
$i += 3;
if (!($o2 >= 144 && $o2 <= 191) ||
!($o3 >= 128 && $o3 <= 191) ||
!($o4 >= 128 && $o4 <= 191)) {
$ok = 0;
break;
}
}
elseif ($o >= 241 && $o <= 243) {
$o2 = ord(mb_substr($string, $i + 1, 1, "ISO-8859-1"));
$o3 = ord(mb_substr($string, $i + 2, 1, "ISO-8859-1"));
$o4 = ord(mb_substr($string, $i + 3, 1, "ISO-8859-1"));
$i += 3;
if (!($o2 >= 128 && $o2 <= 191) ||
!($o3 >= 128 && $o3 <= 191) ||
!($o4 >= 128 && $o4 <= 191)) {
$ok = 0;
break;
}
}
elseif ($o == 244) {
$o2 = ord(mb_substr($string, $i + 1, 1, "ISO-8859-1"));
$o3 = ord(mb_substr($string, $i + 2, 1, "ISO-8859-1"));
$o4 = ord(mb_substr($string, $i + 3, 1, "ISO-8859-1"));
$i += 5;
if (!($o2 >= 128 && $o2 <= 143) ||
!($o3 >= 128 && $o3 <= 191) ||
!($o4 >= 128 && $o4 <= 191)) {
$ok = 0;
break;
}
}
else {
$ok = 0;
break;
}
}
return $ok;
}
```
Yes, it's very long. I hope I've understood correctly how that regular expression works. Also hope it will be of help to others.
Thanks in advance! | You can always using the [Multibyte String Functions](https://www.php.net/manual/en/function.mb-internal-encoding.php):
If you want to use it a lot and possibly change it at sometime:
1. First set the encoding you want to use in your config file
/\* Set internal character encoding to UTF-8 \*/
mb\_internal\_encoding("UTF-8");
2. Check the String
if(mb\_check\_encoding($string))
{
// do something
}
Or, if you don't plan on changing it, you can always just put the encoding straight into the function:
```
if(mb_check_encoding($string, 'UTF-8'))
{
// do something
}
``` | Given that there is still no explicit isUtf8() function in PHP, here's how UTF-8 can be accurately validated in PHP depending on your PHP version.
Easiest and most backwards compatible way to properly validate UTF-8 is still via regular expression using function such as:
```
function isValid($string)
{
return preg_match(
'/\A(?>
[\x00-\x7F]+ # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*\z/x',
$string
) === 1;
}
```
Note the two key differences to the regular expression offered by W3C. It uses once only subpattern and has a '+' quantifier after the first character class. The problem of PCRE crashing still persists, but most of it is caused by using repeating capturing subpattern. By turning the pattern to a once only pattern and capturing multiple single byte characters in single subpattern, it should prevent PCRE from quickly running out of stack (and causing a segfault). Unless you're validating strings with lots of multibyte characters (in the range of thousands), this regular expression should serve you well.
Another good alternative is using `mb_check_encoding()` if you have the mbstring extension available. Validating UTF-8 can be done as simply as:
```
function isValid($string)
{
return mb_check_encoding($string, 'UTF-8') === true;
}
```
Note, however, that if you're using PHP version prior to **5.4.0**, this function has some flaws in it's validation:
* Prior to **5.4.0** the function accepts code point beyond allowed Unicode range. This means it also allows 5 and 6 byte UTF-8 characters.
* Prior to **5.3.0** the function accepts surrogate code points as valid UTF-8 characters.
* Prior to **5.2.5** the function is completely unusable due to not working as intended.
---
As the internet also lists numerous other ways to validate UTF-8, I will discuss some of them here. Note that **the following should be avoided** in most cases.
Use of `mb_detect_encoding()` is sometimes seen to validate UTF-8. If you have at least PHP version **5.4.0**, it does actually work with the strict parameter via:
```
function isValid($string)
{
return mb_detect_encoding($string, 'UTF-8', true) === 'UTF-8';
}
```
It is very important to understand that this does not work prior to **5.4.0**. It's very flawed prior to that version, since it only checks for invalid sequences but allows overlong sequences and invalid code points. In addition, you should never use it for this purpose without the strict parameter set to true (it does not actually do validation without the strict parameter).
One nifty way to validate UTF-8 is via the use of 'u' flag in PCRE. Though poorly documented, it also validates the subject string. An example could be:
```
function isValid($string)
{
return preg_match('//u', $string) === 1;
}
```
Every string should match an empty pattern, but usage of the 'u' flag will only match on valid UTF-8 strings. However, unless you're using at least **5.5.10**. The validation is flawed as follows:
* Prior to **5.5.10**, it does not recognize 3 and 4 byte sequences as valid UTF-8. As it excludes most of unicode code points, this is pretty major flaw.
* Prior to **5.2.5** it also allows surrogates and code points beyond allowed unicode space (e.g. 5 and 6 byte characters)
Using the 'u' flag behavior does have one advantage though: It's the fastest of the discussed methods. If you need speed and you're running the latest and greatest PHP version, this validation method might be for you.
One additional way to validate for UTF-8 is via `json_encode()`, which expects input strings to be in UTF-8. It does not work prior to **5.5.0**, but after that, invalid sequences return false instead of a string. For example:
```
function isValid($string)
{
return json_encode($string) !== false;
}
```
I would not recommend on relying on this behavior to last, however. Previous PHP versions simply produced an error on invalid sequences, so there is no guarantee that the current behavior is final. | UTF-8 validation in PHP without using preg_match() | [
"",
"php",
"regex",
"validation",
"utf-8",
""
] |
I have an existing java webapp that uses Hibernate for it's persistence. I've been told that I have to have to talk to the DB encrypted - so my first thought is to set it up to do the communication via SSL - and went through figured out how to set up Oracle to listen for JDBC over SSL -
`http://www.oracle.com/technology/tech/java/sqlj_jdbc/pdf/wp-oracle-jdbc_thin_ssl_2007.pdf`
And wrote a quick test class to verify that it was setup and working (connecting via standard JDBC). That left me with the issue of configuring Hibernate - unfortunately I don't see how hibernate supports it? | Hibernate works with standard JDBC data sources, so there is no need for Hibernate-specific configuration.
Here's an quick example that should work when configuring Hibernate with Spring:
```
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
<property name="URL"><value><!-- JDBC URL that specifies SSL connection --></value></property>
<!-- other relevant properties, like user and password -->
<property name="connectionProperties>
<value>
oracle.net.ssl_cipher_suites: (ssl_rsa_export_with_rc4_40_md5, ssl_rsa_export_with_des40_cbc_sha)
oracle.net.ssl_client_authentication: false
oracle.net.ssl_version: 3.0
oracle.net.encryption_client: REJECTED
oracle.net.crypto_checksum_client: REJECTED
</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- classes etc -->
</bean>
``` | Try this:
```
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://blablaba:8443/dbname?useSSL=true</property>
<property name="hibernate.connection.verifyServerCertificate">false</property>
<property name="hibernate.connection.requireSSL">true</property>
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.connection.username">bablablab</property>
<property name="hibernate.connection.password">clclclclc</property>
```
related links
<http://www.razorsql.com/articles/mysql_ssl_jdbc.html>
<http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-using-ssl.html>
<http://www.javabeat.net/qna/164-hibernate-jdbc-and-connection-properties/> | How can I configure Hibernate to use SSL to talk to the DB server? | [
"",
"java",
"hibernate",
"configuration",
""
] |
How do I mock an object with a constructor using Rhino Mocks?
For example how would this object be mocked...
```
public class Foo : IFoo
{
private IBar bar;
public Foo (IBar bar)
{
this.bar = bar
}
public DoSomeThingAwesome()
{
//awesomeness happens here
}
}
``` | You don't mock `Foo` - you mock `IFoo`. To test `Foo` itself, you mock `IBar` and pass the mock into the constructor.
You should try to avoid having things which rely on `IFoo` explicitly constructing instances of `Foo`: they should either be given a factory if `IFoo` somehow, or have an `IFoo` explicitly passed to them. | ```
var myIFoo = MockRepository.GenerateStub<IFoo>();
```
you can check awesomeness happened via
```
myIFoo.AssertWasCalled(f => f.DoSomethingAwesome());
``` | Mock an object with a constructor - Rhino Mocks | [
"",
"c#",
"rhino-mocks",
""
] |
In the book [Java Servlet Programming](https://rads.stackoverflow.com/amzn/click/com/0596000405), there's an example servlet on page 54 which searches for primes in a background thread. Each time a client accesses the servlet, the most recently found prime number is returned.
The variable which is used to store the most recently found prime is declared as such:
```
long lastprime = 0;
```
Since this variable is begin accessed from multiple threads (the background thread that's doing the calculations and any client threads that are accessing it), doesn't it need to be declared volatile or have its access synchronized in some way? | Yes, assuming you really want to see the most recently calculated prime on any thread, it should either be volatile or be accessed in a thread-safe way via `synchronized` blocks/methods. Additionally, as pointed out in the comments, non-volatile long variables may not be updated atomically - so you could see the top 32 bits of an old value and the bottom 32 bits of a new value (or vice versa).
I forgot about the atomicity side of things earlier because it's almost *always* solved automatically by when you make sure you get the most recently published value, and make sure you fully publish new values. In practice this is almost always what you want, so atomicity becomes a non-issue if your code is working properly to start with.
It's not a `SingleThreadModel` servlet is it? That would obviously make a difference.
Another alternative would have been to use [`AtomicLong`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicLong.html). | Yes. A servlet's variables aren't thread-safe. | Does a variable accessed by multiple threads in a java servlet need to be declared volatile? | [
"",
"java",
"servlets",
"concurrency",
"multithreading",
""
] |
I'm working on a program to solve the *n* queens problem ([the problem](http://en.wikipedia.org/wiki/Eight_queens_puzzle) of putting *n* chess queens on an *n* x *n* chessboard such that none of them is able to capture any other using the standard chess queen's moves). I am using a heuristic algorithm, and it starts by placing one queen in each row and picking a column randomly out of the columns that are not already occupied. I feel that this step is an opportunity for optimization. Here is the code (in C++):
```
vector<int> colsleft;
//fills the vector sequentially with integer values
for (int c=0; c < size; c++)
colsleft.push_back(c);
for (int i=0; i < size; i++)
{
vector<int>::iterator randplace = colsleft.begin() + rand()%colsleft.size();
/* chboard is an integer array, with each entry representing a row
and holding the column position of the queen in that row */
chboard[i] = *randplace;
colsleft.erase(randplace);
}
```
If it is not clear from the code: I start by building a vector containing an integer for each column. Then, for each row, I pick a random entry in the vector, assign its value to that row's entry in `chboard[]`. I then remove that entry from the vector so it is not available for any other queens.
I'm curious about methods that could use arrays and pointers instead of a vector. Or `<list>`s? Is there a better way of filling the vector sequentially, other than the `for` loop? I would love to hear some suggestions! | The following should fulfill your needs:
```
#include <algorithm>
...
int randplace[size];
for (int i = 0; i < size; i ++)
randplace[i] = i;
random_shuffle(randplace, randplace + size);
```
You can do the same stuff with vectors, too, if you wish.
Source: <http://gethelp.devx.com/techtips/cpp_pro/10min/10min1299.asp> | Couple of random answers to some of your questions :):
1. As far as I know, there's no way to fill an array with consecutive values without iterating over it first. HOWEVER, if you really just need consecutive values, you do not need to fill the array - just use the cell indices as the values: a[0] is 0 and a[100] is 100 - when you get a random number, treat the number as the value.
2. You can implement the same with a list<> and remove cells you already hit, or...
3. For better performance, rather than removing cells, why not put an "already used" value in them (like -1) and check for that. Say you get a random number like 73, and a[73] contains -1, you just get a new random number.
4. Finally, describing item 3 reminded me of a re-hashing function. Perhaps you can implement your algorithm as a hash-table? | Fast way to pick randomly from a set, with each entry picked only once? | [
"",
"c++",
"optimization",
"random",
"puzzle",
""
] |
Example:
```
myEnumerable.Select(a => ThisMethodMayThrowExceptions(a));
```
How to make it work even if it throws exceptions? Like a try catch block with a default value case an exceptions is thrown... | ```
myEnumerable.Select(a =>
{
try
{
return ThisMethodMayThrowExceptions(a));
}
catch(Exception)
{
return defaultValue;
}
});
```
But actually, it has some smell.
About the lambda syntax:
```
x => x.something
```
is kind of a shortcut and could be written as
```
(x) => { return x.something; }
``` | Call a projection which has that try/catch:
```
myEnumerable.Select(a => TryThisMethod(a));
...
public static Bar TryThisMethod(Foo a)
{
try
{
return ThisMethodMayThrowExceptions(a);
}
catch(BarNotFoundException)
{
return Bar.Default;
}
}
```
Admittedly I'd *rarely* want to use this technique. It feels like an abuse of exceptions in general, but sometimes there are APIs which leave you no choice.
(I'd almost certainly put it in a separate method rather than putting it "inline" as a lambda expression though.) | Is it possible to handle exceptions within LINQ queries? | [
"",
"c#",
".net",
"linq",
"exception",
""
] |
I am serializing a XML File.During the serialization ,I am receiving general exception.It is hard trace the problem.
my code is:
---
try
{
string m\_fileName = @"d:\Xml\Person.xml";
XmlSerializer xmlPerSerlzr = new XmlSerializer(typeof(person));
txtWrt = new StreamWriter(m\_fileName);
---
Error Message :
There was an error reflecting type "Person"
---
My question is how can i force the CLR to emit the exact error ? | I think it is better to check also the stack trace and the inner exception.
You can use something like that
```
string GetExceptionString(Exception ex)
{
string str = "";
while (ex != null)
{
str += ex.Message + "\n" + ex.StackTrace;
ex = ex.InnerException;
}
return str;
}
``` | Check the type of the exception, e.g.
```
serExp.GetType().ToString()
```
and check for an inner exception (both type and message).
That should give you some more useful info. | Unable to Catch Specific Exception | [
"",
"c#",
""
] |
I'm in the process of reformatting my class ( seen below ) - I think I made the mistake of setting everything with the same visibility in my class, whereas properties should really be private and getters/setters should be public in most cases.
To grab a property I just do $path->propertyname but I've noticed its more practical to have setters/getters. If I were to implement getters, should I make one for each property or can I make one for the entire class? So for example say I want to get the controller name...
```
public function getController( ) {
return $this->controller;
}
```
And that would return the controller private property? Is it common to have a more generic getter/setter or even a hybrid method that gets *and* sets for me?
Here's the class structure ( just properties/methods ):
```
class urlParser {
public static $url = '';
public static $controller = '';
public static $baseController = '';
public static $urls = '';
public static $template = '';
public static $captures = '';
public static $contentXML = '';
function __construct( $urls ) {
$this->urls = $urls;
$this->baseController = $urls['default'];
$this->get_url();
}
public function get_url() {
// sets following properties:
// url, template, controller, contentXML, baseController
}
}
``` | Having setters and getters in you case is pointless.
In case you have to do anything besides returning controller, you don't need getter as you don't need setter if you don't do anything with property after it has been set.
In case you really want getters and setters, you can use \_\_get and \_\_set magic methods for all your properties. But that is totally pointless if the case is as I described above. | take a look at overloading in php: <http://php.net/overload>
there are two magic methods `__get()` and `__set()` which might do exactly what you want | Setters/Getters, Visibility [ OOP ] in PHP | [
"",
"php",
"oop",
"visibility",
"setter",
"getter",
""
] |
Can I remove any implicitly imported Java library?
It may not seem useful.
But I think it may reduce some execution time! | Imports are just syntactic sugar. All they do is let you access things in other packages without having to state their fully qualified name. The code that is produced is exactly the same as if you fully-qualified everything. So there is no runtime performance penalty to having imports.
This also goes for the "implicit imports" (ie: java.lang): you don't pay any price for the classes you don't actually use. | This will have no effect on execution type - I think I'm correct in saying that, by default, classes are only loaded as and when they are needed, not on mass at start-up.
To improve performance you need to profile your application with a tool like [Visual VM](https://visualvm.dev.java.net/) and address the bottlenecks it identifies (which will never be where you'd expect). | Can I remove any implicitly imported Java library? | [
"",
"java",
"import",
""
] |
I am looking for a performant default policy for dealing with the .dbo prefix.
I realize that the dbo. prefix is more than syntactic noise, however I got through the past 8 years of MS based development skipping typing the dbo. prefix and ignoring its function.
Apart from a performance issue with stored proc compile locks is there a downside to skipping typing ".dbo" in SQLqueries and stored procedures?
Further background: All my development is web middle-tier based with integrated security based on a middle tier service account. | [dbo].[xxx]
The SQL Server engine always parse the query into pieces, if you don't use the prefix definitely it going search for object in similar name with different users before it uses [dbo]. I would suggest you follow the prefix mechanism not only to satisfy the best practices, also to avoid performance glitches and make the code scalable.
I don't know I answered your question, but these are just my knowledge share | Most of the time you can ignore it. Sometimes you will have to type it. Sometimes when you have to type it you can just type an extra '.':
```
SELECT * FROM [LinkedServer].[Database]..[Table]
```
You'll need to start watching for it if you start using extra schemas a lot more, where you might have two schemas in the same database that both have tables with the same name. | The dbo. prefix in database object names, can I ignore it? | [
"",
"sql",
"sql-server",
""
] |
I am getting this error when I try to set a mock to have `PropertyBehavior()`:
> System.InvalidOperationException: System.InvalidOperationException:
> Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)..
I am trying to use only [Rhino Mocks 3.5](http://ayende.com/wiki/Rhino%20Mocks%203.5.ashx) (Arrange, Act, Assert)
Here is my code:
```
private IAddAddressForm form;
private AddAddressMediator mediator;
[TestInitialize()]
public void MyTestInitialize()
{
form = MockRepository.GenerateMock<IAddAddressForm>();
mediator = new AddAddressMediator(form);
// Make the properties work like a normal property
Expect.Call(form.OKButtonEnabled).PropertyBehavior();
//I tried this too. I still get the exception
//SetupResult.For(form.OKButtonEnabled).PropertyBehavior();
}
[TestMethod]
public void TestOKButtonEnabled()
{
form.OKButtonEnabled = true;
Assert.IsTrue(form.OKButtonEnabled);
}
```
I know I could use a stub (and for the code above I should) but I am trying to learn Rhino Mocks.
Eventually I want to be able to make sure that several properties has their values accessed. (Any hints on how to check that `form.FirstName` was accessed (i.e. the getter was called) would also be appreciated.)
In case it is needed, here is the code to `IAddressForm`:
```
namespace AddressBook
{
public interface IAddAddressForm
{
string FirstName { get; set; }
string LastName { get; set; }
string Address1 { get; set; }
string State { get; set; }
string Address2 { get; set; }
string ZipCode { get; set; }
string City { get; set; }
bool OKButtonEnabled { get; set; }
}
}
```
Anyway, I thought that virtual would not be a problem as I am passing in an interface, but I am clearly missing something. | Never used `PropertyBehavior` before, but is this the syntax you're looking for?
```
form.Stub(x=>x.OKButtonEnabled).PropertyBehavior()
```
Rhino Mocks works completely through extension methods now. The only static call I every make any more is to `MockRepository.GenerateStub`. | You mentioned using a stub instead of a mock but before you go changing it I'd note that strangely, I get the Invalid Call exception when I used GenerateStub but not when I use GenerateMock.
```
View = MockRepository.GenerateStub<IAddressView>();
View.Stub(v => v.Message).PropertyBehavior();
```
This throws the Invalid call exception and yes, IAddressView.Message does have a getter and setter. | Invalid call, the last call has been used or no call has been made | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"rhino-mocks",
"rhino-mocks-3.5",
""
] |
I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute `import gobject` I get this:
```
Traceback (most recent call last):
import gobject
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, in <module>
from gobject.constants import *
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\constants.py", line 22, in <module>
from _gobject import type_from_name
ImportError: DLL load failed: The specified procedure could not be found.
```
This appears to be caused by the switch from building using MinGW to Microsoft Visual Studio, as documented [Python Bug 3308](http://bugs.python.org/issue3308) (`closed: wontfix`).
Is there any way to install PyGTK/PyGObject in a way that will work with Python 2.6 on Windows, without having to recompile one or the other from source? | I have it working fine, and it didn't give me much trouble, so we know it can be done...
Keep in mind you will probably need all of the following installed on your Windows machine:
* PyCairo ( <http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/> )
* PyGobject ( <http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/> )
* PyGTK ( <http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/> )
*Unofficial* x64 versions of the above 3 items are available [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygtk) -- However, I cannot vouch for nor recommend them!
and of course
* the GTK+ Runtime ( <http://ftp.gnome.org/pub/GNOME/binaries/win32/gtk+/> or <http://ftp.gnome.org/pub/GNOME/binaries/win64/gtk+/> )
I suspect in your case that the PyGTK libraries are not finding your GTK+ Runtime directory where the DLLs are. You should have the environment variable GTK\_BASEPATH set to the directory of your GTK+ Runtime (usually C:\GTK).
Please also see the [PyGTK-on-Windows FAQ](http://faq.pygtk.org/index.py?req=show&file=faq21.001.htp)
Now, if you're trying to compile the PyGTK'ed Python with Py2EXE, that's a bit more complicated, but it can be done as well... | The PyGTK all-in-one installer has been updated recently:
<http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/>
This will install PyGTK, PyGObject, PyCairo, PyGtkSourceView2, PyGooCanvas, PyRsvg, the gtk+-bundle and Glade. It is absolutely everything necessary to be able to successfully `import gobject`, `import gtk`, etc, without DLL problems. | How do I install PyGTK / PyGobject on Windows with Python 2.6? | [
"",
"python",
"pygtk",
"mingw",
"pygobject",
""
] |
I have read a few bits and bobs online about this topic but found none that work for me.
What I am trying to do is create a class of a runtime Type.
I use `Activator.CreateInstance` which works fine for classes with constructors that contain no arguments. For those with arguments it throws an exception, is there a way around this?
I am more than happy to pass null values or empty values to the ctor so long as I can create the class itself. | I eventually ended up doing something like this - some of the commentors hinted towards this solution anyway.
I basically iterated through all available constructors and chose the simplest. I then created null data to pass into the ctor (for what Im using it for this approach is fine)
Part of the code looks a little like this
```
// If we have a ctor that requires parameters then pass null values
if (requiresParameters)
{
List<object> parameters = new List<object>();
ParameterInfo[] pInfos = constructorInfos[0].GetParameters();
foreach (ParameterInfo pi in pInfos)
{
parameters.Add(createType(pi.ParameterType));
}
return constructorInfos[0].Invoke(parameters.ToArray());
}
``` | There is an overload that accepts arguments as a `params object[]`:
```
object obj = Activator.CreateInstance(typeof(StringBuilder), "abc");
```
Would this do? Alternative, you can use reflection to find the correct constructor:
```
Type[] argTypes = new Type[] {typeof(string)};
object[] argValues = new object[] {"abc"};
ConstructorInfo ctor = typeof(StringBuilder).GetConstructor(argTypes);
object obj = ctor.Invoke(argValues);
``` | Activator.CreateInstance - How to create instances of classes that have parameterized constructors | [
"",
"c#",
".net",
".net-3.5",
""
] |
> **Possible Duplicate:**
> [Why don’t self-closing script tags work?](https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work)
I had this bit of javascript code inside a <head> element.
```
<script src="jquery-1.3.2.js" type="text/javascript" />
<script type="text/javascript">
$(document).ready(function() {
$("#welcome").addClass("centered");
$("#created").addClass("centered");
});
</script>
```
Which refused to work until I used an explicit end script element:
```
<script src="jquery-1.3.2.js" type="text/javascript"></script>
```
Why is there a difference?
EDIT: the entire header was:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/blueprint/print.css" type="text/css" media="print" />
<!--[if lt IE 8]><link rel="stylesheet" href="css/blueprint/ie.css" type="text/css" media="screen, projection" /><![endif]-->
<link rel="stylesheet" href="css/blueprint/src/typography.css" />
<link rel="stylesheet" href="css/common.css" />
<script src="jquery-1.3.2.js" type="text/javascript" />
<script type="text/javascript">
$(document).ready(function() {
$("#welcome").addClass("centered");
$("#created").addClass("centered");
});
</script>
</head>
```
I don't understand why the script element needs an explicit end element but the link element doesnt. | Yeah, you always need to end script elements like that. It doesn't support the XHTML format of ' />' to end the tag. | What is the doctype of your document? Technically minimized tags like your first example are an XML-only thing. In most cases HTML allow them, but the correct HTML is your second example. | weird javascript/jquery behavior | [
"",
"javascript",
"jquery",
""
] |
here is the code im having trouble with
```
$key = array(
"0" => "sss",
"1" => "wst",
"2" => "sfv",
"3" => "lac",
"4" => "sgv",
"5" => "lgb",
"6" => "ant"
);
$urls = array(
"0" => "http://www.sarmenhb.com/index.php?key=",
"1" => "http://www.navidoor.com/index.php?key=",
"2" => "http://www.worldexchange.com/index.php?key=",
"3" => "http://www.iaddesign.com/index.php?key=",
"4" => "http://www.iadesignandstudio.com/index.php?key=",
"5" => "http://www.redlineautoleasing.com/index.php?key="
);
for($a=0;$a <= count($urls);$a++) {
foreach($key as $keys) {
print $urls[$a].$keys[$a]."<br/>";
}
}
print "<br/><br/>";
```
i am trying to make the output look like this:
```
http://www.sarmenhb.com/index.php?key=sss
http://www.navidoor.com/index.php?key=sss
http://www.worldexchange.com/index.php?key=sss
http://www.iaddesign.com/index.php?key=sss
http://www.iadesignandstudio.com/index.php?key=sss
http://www.redlineautoleasing.com/index.php?key=sss
http://www.sarmenhb.com/index.php?key=wst
http://www.navidoor.com/index.php?key=wst
http://www.worldexchange.com/index.php?key=wst
http://www.iaddesign.com/index.php?key=wst
http://www.iadesignandstudio.com/index.php?key=wst
http://www.redlineautoleasing.com/index.php?key=wst
etc including all key values included as a value the the param key
```
ive removed the origional urls to prevent url hacking but how can i print an output like that?
the output i keep getting is key=s or key=w the whole key value isnt displaying. along with an error of Notice: Uninitialized string offset: 3 in D:\wamp\www\MVC\t.php on line 32
please help
thank alot! | ```
foreach($key as $string)
{
foreach($urls as $address)
{
echo $address . $string . "<br/>";
}
}
``` | I would simply do two foreach statements:
```
foreach($urls as $url) {
foreach($keys as $key) {
print $url.$key."\n";
}
}
```
I also recommend you to pluralize the name of your arrays for simple readability, check the output [here](http://codepad.org/fiPYqVny). | trying to figure out how to write this with arrays | [
"",
"php",
""
] |
Using Visual Studio 2005 - C# 2.0, `System.Net.WebClient.UploadData(Uri address, byte[] data)` Windows Server 2003
So here's a stripped down version of the code:
```
static string SO_method(String fullRequestString)
{
string theUriStringToUse = @"https://10.10.10.10:443"; // populated with real endpoint IP:port
string proxyAddressAndPort = @"http://10.10.10.10:80/"; // populated with a real proxy IP:port
Byte[] utf8EncodedResponse; // for the return data in utf8
string responseString; // for the return data in utf16
WebClient myWebClient = new WebClient(); // instantiate a web client
WebProxy proxyObject = new WebProxy(proxyAddressAndPort, true);// instantiate & popuylate a web proxy
myWebClient.Proxy = proxyObject; // add the proxy to the client
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); // stick some stuff in the header
UTF8Encoding utf8Encoding = new UTF8Encoding(false);// create a utf8 encoding
Byte[] utf8EncodedRequest = HttpUtility.UrlEncodeToBytes(fullRequestString, utf8Encoding); // convert the request data to a utf8 byte array
try
{
utf8EncodedResponse = myWebClient.UploadData(theUriStringToUse, "POST", utf8EncodedRequest); // pass the utf8-encoded byte array
responseString = utf8Encoding.GetString(utf8EncodedResponse); // get a useable string out of the response
}
catch (Exception e)
{
// some other error handling
responseString = "<CommError><![CDATA[" + e.ToString() + "]]></CommError>";// show the basics of the problem
}
return responseString;// return whatever ya got
}
```
This is the error I get:
> **The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.**
I don't have much control to see what's happening when the request goes out. I'm told that it's reaching the correct destination and there's a "certificate error". This is supposedly because there's a literal mismatch between the IP address in my request and the URL it resolves to. I have more than one IP I'm supposed to round-robin to so specifying the URL won't work. I'm not attaching a certificate - nor am I supposed to according to the endpoint owners. Per "them" the certificate error is 'normal and I am supposed to ignore it.
The cert in question is supposedly one of the many verisign certs that is "just there" on our server. The examples I've seen for ignoring cert errors all seem to imply that the requestor is attaching a specific x509 certificate (which I'm not).
I looked over [.net WebService, bypass ssl validation!](https://stackoverflow.com/questions/721472/net-webservice-bypass-ssl-validation) which kinda-sorta describes my problem - except it also kinda-sorta doesn't because I don't know which certificate (if any) I should reference.
Is there a way for me to ignore the error without actually knowing/caring what certificate is causing the problem?
* and please - kid gloves, small words, and "for dummies" code as I'm not exactly a heavy hitter.
* This traffic is over a private line - so my understanding is that ignoring the cert error is not as big a deal as if it were open internet traffic. | The SSL certificate is for a machine to establish a trust relationship. If you type in one IP address, and end up talking to another, that sounds the same as a DNS hijack security fault, the kind of thing SSL is intending to help you avoid - and perhaps something you don't want to put up with from "them".
If you may end up talking to more than machine (ideally they would make it appear as one for you), you will need a certificate for each of the possible machines to initiate trust.
To ignore trust (I've only ever had to do this temporarily in development scenarios) the following snippet may work for you, but I strongly recommend you consider the impact of ignoring trust before using it:
```
public static void InitiateSSLTrust()
{
try
{
//Change SSL checks so that all checks pass
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate
{ return true; }
);
}
catch (Exception ex)
{
ActivityLog.InsertSyncActivity(ex);
}
}
``` | I realize this is an old post, but I just wanted to show that there is a more short-hand way of doing this (with .NET 3.5+ and later).
Maybe it's just my OCD, but I wanted to minimize this code as much as possible. This seems to be the shortest way to do it, but I've also listed some longer equivalents below:
```
// 79 Characters (72 without spaces)
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
```
Shortest way in .NET 2.0 (which is what the question was specifically asking about)
```
// 84 Characters
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
```
It's unfortunate that the lambda way requires you to define the parameters, otherwise it could be even shorter.
And in case you need a much longer way, here are some additional alternatives:
```
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => true;
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
// 255 characters - lots of code!
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
});
``` | How to ignore a certificate error with c# 2.0 WebClient - without the certificate | [
"",
"c#",
"ssl-certificate",
"webclient",
""
] |
I am using C# + VSTS2008 + .Net 3.0. I have an input as a string array. And I need to output the unique strings of the array. Any ideas how to implement this efficiently?
For example, I have input {"abc", "abcd", "abcd"}, the output I want to be is {"abc", "abcd"}. | Using LINQ:
```
var uniquevalues = list.Distinct();
```
That gives you an `IEnumerable<string>`.
If you want an array:
```
string[] uniquevalues = list.Distinct().ToArray();
```
---
If you are not using .NET 3.5, it's a little more complicated:
```
List<string> newList = new List<string>();
foreach (string s in list)
{
if (!newList.Contains(s))
newList.Add(s);
}
// newList contains the unique values
```
Another solution (maybe a little faster):
```
Dictionary<string,bool> dic = new Dictionary<string,bool>();
foreach (string s in list)
{
dic[s] = true;
}
List<string> newList = new List<string>(dic.Keys);
// newList contains the unique values
``` | Another option is to use a `HashSet`:
```
HashSet<string> hash = new HashSet<string>(inputStrings);
```
I think I'd also go with linq, but it's also an option.
Edit:
You've update the question to 3.0, maybe this will help:
[Using HashSet in C# 2.0, compatible with 3.5](https://stackoverflow.com/questions/687034/using-hashset-in-c-2-0-compatible-with-3-5) | How to get unique values from a collection in C#? | [
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I have a simple C++ program compiled using gcc 4.2.4 on 32-bit Ubuntu 8.04. It has a `for`-loop in which a `double` variable is incremented from zero to one with a certain step size. When the step size is `0.1`, the behavior is what I expected. But when the step size is '0.05', the loop exits after `0.95`. Can anyone tell me why this is happening? The output follows the source code below.
```
#include <iostream>
using namespace std;
int main()
{
double rangeMin = 0.0;
double rangeMax = 1.0;
double stepSize = 0.1;
for (double index = rangeMin; index <= rangeMax; index+= stepSize)
{
cout << index << endl;
}
cout << endl;
stepSize = 0.05;
for (double index = rangeMin; index <= rangeMax; index+= stepSize)
{
cout << index << endl;
}
return 0;
}
```
OUTPUT
```
sarva@savija-dev:~/code/scratch$ ./a.out
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95
sarva@savija-dev:~/code/scratch$
``` | When using floating point values not every value is exactly representable, `0.95+0.05 > 1` because `0.95` is not exactly representable by a `double` value.
See what Wikipedia has to say about [floating point accuracy](http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
If you look at the [IEEE floating point converter](http://www.h-schmidt.net/FloatConverter/IEEE754.html) you'll see that the value of `0.95` in 64 bit floating point (`double`) is `0-01111111110-1110011001100110011001100110011001100110011001100110` by entering this in a [floating point calculator](http://www.ajdesigner.com/fl_ieee_754_word/ieee_32_bit_word.php) you get the value is `0.95000016` and adding `0.05` to that takes you over the `1.0` mark.
This is why you should never use floating points in loops (or more generally compare the result of floating point calculation to an **exact** value). | Generally, when you compare doubles, simple comparison is not good enough, and you should compare them "up to a precision". i.e. :
```
if ( fabs(double1-double2) < 0.0000001 ) {
do-something
}
```
The problem occurs due to the [representation of double variables](http://en.wikipedia.org/wiki/Floating_point). | For-loop in C++ using double breaking out one step early, boundary value not reached | [
"",
"c++",
"for-loop",
"floating-accuracy",
""
] |
What is the equivalent of a Java applet in .NET? Is it Silverlight? Is Java applet still widely in use? | Java applets were "the new hot thing" in 1997, when Java 1.0 came out. After a few years, they became less and less popular, mainly because installing Java on a computer was a big hurdle for many people (you had to download the whole JRE, which was big, it took a long time to install and Java was not that fast at that time - so many people saw it as a slow, bloated thing).
Macromedia Flash (which became Adobe Flash later, ofcourse) had advantages over Java applets in this regard - the plug-in was quick and easy to install, and so it became the dominant thing for interactive multimedia stuff on the web.
Microsoft's Silverlight is meant to be a competitor for Flash and Sun's JavaFX.
[JavaFX](http://javafx.com/) is Sun's technology that should make it easy to do Flash-like things on the Java virtual machine. If JavaFX becomes a success, then Java applets using JavaFX might become popular again.
Note that earlier this year, Sun released a completely rewritten Java browser plug-in which is quicker and easier to install than the old plug-in. On of the things Sun is working on is making it just as easy to install the Java plug-in as it is to install the Flash plug-in. | Silverlight is analagous to Java applets, but not really equivalent. In my experience, Java applets are being used less and less. | What is the equivalent of a Java applet in .NET? | [
"",
"java",
".net",
"applet",
""
] |
I have the following questions:
1. Is it possible to compile a C# project using VS.NET, and run it on mono?
2. Are there any performance benefits associated with approach 1 (vs compiling with the mono compiler)?
3. What about running the output .exe/.dll on linux? And what are the associated performance characteristics?
Thanks | 1. Yes, you can do that. It should work unless the code uses some framework elements that are not implemented on mono.
2. Not that I am aware of.
3. Not sure what the difference between #3 and #1 is. If you are referring to using mono to compile on Windows, then porting it to linux, it should still work the same. Both compilers generate essentially the same IL code. | 1:
Yes. The compilers compile into IL code, which runs in either system.
Not every library is implemented in Mono, but those that are should work seamlessly. Also, the code has to be written to be independend of the system to work properly, for example:
* Use `Path.DirectorySeparatorChar` and `Path.Combine` to form file paths, instead of using the string literal `"\"` or `"/"`.
* Use the BitConverter class to do byte manipulation that is independend of big-endian / little-endian achitecture.
2:
There may be some differences in what code the compilers generate, but as almost all optimising is done by the JIT compiler that should rarely make any measurable difference.
3:
The exe and dll files does not contain native code, they contain IL code. The native code is generated by the JIT compiler when the exe/dll is loaded. | Performance: Compile in VS, Run in Mono on Windows and Linux | [
"",
"c#",
".net",
"linux",
"performance",
"mono",
""
] |
I have this snippet of code here. The intention is to make a copy of initialData. Since I am not modifying initialData in any way, I figure that I should pass it as a const reference. However, I keep getting this message when compiling.
> .\src\Scene\SceneAnimationData.cpp(23)
> : error C2662:
> 'SceneTrackerData::getRect' : cannot
> convert 'this' pointer from 'const
> SceneTrackerData' to 'SceneTrackerData
> &'
```
#include "SceneTrackerData.h"
void SceneAnimationData::SetupData(const SceneTrackerData &initialData)
{
// getRect(), points() and links() all return const pointers
CloneRect(initialData.getRect());
ClonePoints(initialData.points()->values());
CloneLinks(initialData.links()->values());
}
void SceneAnimationData::CloneRect(const QGraphicsRectItem * initialRect)
{
if (initialRect != NULL)
{
QPointF position = initialRect->scenePos();
QRectF rect = initialRect->rect();
initialRect = new QGraphicsRectItem(rect);
initialRect->setPos(position);
}
}
void SceneAnimationData::CloneLinks(const QList<QGraphicsLineItem*> links)
{
links_ = new QList<QGraphicsLineItem*>(*links);
}
void SceneAnimationData::ClonePoints(const QList<QGraphicsEllipseItem*> points)
{
points_ = new QList<QGraphicsEllipseItem*>(*points);
}
``` | Without the definition of `SceneTrackerData`, it's hard to say, but likely that function (`SceneTrackerData::getRect`) is not marked as const.
That is, what is (guessing):
```
const Rect& SceneTrackerData::getRect(void)
```
Should be:
```
const Rect& SceneTrackerData::getRect(void) const
// ^
// |
// does not logically modify the object
``` | It's not clear which is line 23 here; but my guess is that you are calling methods on the object that are not themselves declared as `const` and thus are not usable by a `const` object reference. | C++ and const - accessing a member function of a const reference | [
"",
"c++",
"constants",
""
] |
What is a good simple problem to throw at Jr. and Mid level developers to to find out given the opportunity to Program to an Interface (like a simple Factory pattern) if they will do it? | Get him to log different custom messages (he can hard code them) into different types of files (he can choose an interface or not).
It's simple, and shouldn't take that long. You could help with implementing the methods if that's not the focus of the interview. | Don't limit yourself to that either/or. Give something big enough that a few patterns might emerge.
How about: I want to display a dashboard of some data feeds. The date comes in messages arriving on queues. Some messages being XML, some being a binary format.
Plenty of chance for them to ask questions about the contents. See how they approach that fuzzy requriement. | C# - Programmer Challenge for Interviews - Programming to an Interface & Patterns | [
"",
"c#",
".net",
"design-patterns",
"factory",
""
] |
in my journey of learning hibernate i came across an article on [hibernate site](https://www.hibernate.org/328.html). i' learning spring too and wanted to do certain things to discover the flexibility of spring by letting you implement you own session.yes i don't want to use the hibernateTemplate(for experiment). and i'm now having a problem and even the test class.I followed the article on the hibernate site especially the section an "implementation with hibernate"
so we have the generic dao interface :
```
public interface GenericDAO<T, ID extends Serializable> {
T findById(ID id, boolean lock);
List<T> findAll();
List<T> findByExample(T exampleInstance);
T makePersistent(T entity);
void makeTransient(T entity);
```
}
it's implementation in an abstract class that is the same as the one on the web site.Please refer to it from the link i provide.i'll like to save this post to be too long
now come my dao's messagedao interface
```
package com.project.core.dao;
import com.project.core.model.MessageDetails;
import java.util.List;
public interface MessageDAO extends GenericDAO<MessageDetails, Long>{
//Message class is on of my pojo
public List<Message> GetAllByStatus(String status);
}
```
its implementation is messagedaoimpl:
```
public class MessageDAOImpl extends GenericDAOImpl <Message, Long> implements MessageDAO {
// mySContainer is an interface which my HibernateUtils implement
mySContainer sessionManager;
/**
*
*/
public MessageDAOImpl(){}
/**
*
* @param sessionManager
*/
public MessageDAOImpl(HibernateUtils sessionManager){
this.sessionManager = sessionManager;
}
//........ plus other methods
}
```
here is my HibernatUtils
```
public class HibernateUtils implements SessionContainer {
private final SessionFactory sessionFactory;
private Session session;
public HibernateUtils() {
this.sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
public HibernateUtils(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
*
* this is the function that return a session.So i'm free to implements any type of session in here.
*/
public Session requestSession() {
// if (session != null || session.isOpen()) {
// return session;
// } else {
session = sessionFactory.openSession();
// }
return session;
}
}
```
> So in my understanding while using spring(will provide the conf), i'ld wire sessionFactory to my HiberbernateUtils and then wire its method RequestSession to the Session Property of the GenericDAOImpl (the one from the link provided).
here is my spring config core.xml
```
<bean id="sessionManager" class="com.project.core.dao.hibernate.HibernateUtils">
<constructor-arg ref="sessionFactory" />
</bean>
<bean id="messageDao" class="com.project.core.dao.hibernate.MessageDAOImpl">
<constructor-arg ref="sessionManager"/>
</bean>
<bean id="genericDAOimpl" class="com.project.core.dao.GenericDAO">
<property name="session" ref="mySession"/>
</bean>
<bean id="mySession" factory-bean="com.project.core.dao.SessionContainer" factory-method="requestSession"/>
```
now my test is this
```
public class MessageDetailsDAOImplTest extends AbstractDependencyInjectionSpringContextTests{
HibernateUtils sessionManager = (HibernateUtils) applicationContext.getBean("sessionManager");
MessageDAO messagedao =(MessageDAO) applicationContext.getBean("messageDao");
static Message[] message = new Message[]
{
new Message("text",1,"test for dummies 1","1234567890","Pending",new Date()),
new Message("text",2,"test for dummies 2","334455669990","Delivered",new Date())
};
public MessageDAOImplTest() {
}
@Override
protected String[] getConfigLocations(){
return new String[]{"file:src/main/resources/core.xml"};
}
@Test
public void testMakePersistent() {
System.out.println("MakePersistent");
messagedao.makePersistent(message[0]);
Session session = sessionManager.RequestSession();
session.beginTransaction();
MessageDetails fromdb = ( Message) session.load(Message.class, message[0].getMessageId());
assertEquals(fromdb.getMessageId(), message[0].getMessageId());
assertEquals(fromdb.getDateSent(),message.getDateSent());
assertEquals(fromdb.getGlobalStatus(),message.getGlobalStatus());
assertEquals(fromdb.getNumberOfPages(),message.getNumberOfPages());
}
```
i'm having this error
> exception in constructor testMakePersistent(java.lang.NullPointerException at com.project.core.dao.hibernate.MessageDAOImplTest)
with this stack : at com.project.core.dao.hibernate.MessageDAOImplTest.(MessageDAOImplTest.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at junit.framework.TestSuite.createTest(TestSuite.java:61)
at junit.framework.TestSuite.addTestMethod(TestSuite.java:283)
at junit.framework.TestSuite.(TestSuite.java:146)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:481)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1031)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:888)
))
How to actually make this one work.I know this is a lot to stuffs and i'm thanking you for reading it.Please give me a solution.How would you do this? thanks | Greetings... I think you are making it more complicated than it is. :)
If you are using Spring and Hibernate (which you are), you don't really need to create your own HibernateUtils to manage the session. HibernateUtils is almost required if you don't use Spring, or else it seems redundant. It is tedious, it is one extra code you need to maintain, and you probably are not going to get it right. Your HibernateUtils doesn't seem to be implemented correctly, by the way.
Here's how I would do it:-
1. You need to create a sessionFactory bean:-
```
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>// .. hbm files, omitted for brevity</value>
</list>
</property>
<property name="hibernateProperties">
// .. dialect, etc... omitted for brevity
</property>
</bean>
```
2. Wire this sessionFactory into your DAO (, and you need a setter in your DAO too):-
```
<bean id="messageDao" class="com.project.core.dao.hibernate.MessageDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
```
3. To acquire the connection in your dao, just do sessionFactory.getCurrentSession(). That's it.
You do the same thing by wiring the sessionFactory into your testcase.
Here's some reference if you wish to know how to integrate Spring with Hibernate:
<http://static.springsource.org/spring/docs/2.5.x/reference/orm.html> | It seems to be failing to invoke the **MessageDAOImplTest** constructor, but since it is empty, I'm guessing the problem actually lies in the initialization of the member variables. Which line is line 28? You can try moving the initialization logic to the constructor body and step through it with a debugger to pinpoint the problem.
By the way, your approach has a problem in that the DAOs are singletons shared among all threads, but Hibernate sessions must not be shared across threads, so you need to store them as a **ThreadLocal**. If you use Spring for session management, this happens automatically. Maybe this isn't important to you because this is an "experiment", but I thought I'd bring it up. | testing dao with hibernate genericdao pattern with spring.Headache | [
"",
"java",
"unit-testing",
"hibernate",
"spring",
"jakarta-ee",
""
] |
I'm looking to accept digits and the decimal point, but no sign.
I've looked at samples using the NumericUpDown control for Windows Forms, and [this sample of a NumericUpDown custom control from Microsoft](http://msdn.microsoft.com/en-us/library/ms771573.aspx). But so far it seems like NumericUpDown (supported by WPF or not) is not going to provide the functionality that I want. The way my application is designed, nobody in their right mind is going to want to mess with the arrows. They don't make any practical sense, in the context of my application.
So I'm looking for a simple way to make a standard WPF TextBox accept only the characters that I want. Is this possible? Is it practical? | Add a preview text input event. Like so: `<TextBox PreviewTextInput="PreviewTextInput" />`.
Then inside that set the `e.Handled` if the text isn't allowed. `e.Handled = !IsTextAllowed(e.Text);`
I use a simple regex in `IsTextAllowed` method to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.
```
private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}
```
If you want to prevent pasting of incorrect data hook up the `DataObject.Pasting` event `DataObject.Pasting="TextBoxPasting"` as shown [here](http://karlhulme.wordpress.com/2007/02/15/masking-input-to-a-wpf-textbox/) (code excerpted):
```
// Use the DataObject.Pasting Handler
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
``` | The event handler is previewing text input. Here a regular expression matches the text input only if it is not a number, and then it is not made to entry textbox.
If you want only letters then replace the regular expression as `[^a-zA-Z]`.
## XAML
```
<TextBox Name="NumberTextBox" PreviewTextInput="NumberValidationTextBox"/>
```
## XAML.CS FILE
```
using System.Text.RegularExpressions;
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
``` | How do I get a TextBox to only accept numeric input in WPF? | [
"",
"c#",
"wpf",
"xaml",
"textbox",
"numericupdown",
""
] |
I have the following object:
```
[Serializable]
public class ExampleImage
{
public int ID { get; set; }
public string Filename { get; set; }
public byte[] Content { get; set; }
}
```
I store this in a `List<ExampleImage>` which I then pass to the following function to serialize it to a string:
```
static string SerializeObjectToXmlString(object o)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(o.GetType());
System.IO.StringWriter writer = new System.IO.StringWriter();
serializer.Serialize(writer, o);
return writer.ToString();
}
```
I then pass this serialized string to a stored procedure in **SQL2000** as an `NTEXT` which then handled for inserting it into the database:
```
SELECT * INTO #TempImages
FROM OpenXML(@iDoc, '/ArrayOfExampleImage/ExampleImage')
WITH ([Filename] VARCHAR(255) './Filename', [Content] IMAGE './Content')
```
The problem I am having is the image is getting trashed. The `btye[]` is not getting saved properly to the DB. The other fields are just fine. This is the first time I have attempt to send a binary data via XML to SQL so I am most likely doing something wrong at this point. Is my `SerializeObjectToXmlString` function the problem and it is not handling the serialization of a `byte[]` properly, maybe the `OpenXML` SQL function or even the fact that I am sending the XML in as an `NTEXT` param. I would expect the serialize function to encode the binary properly but I could be wrong.
Any idea what is the issue or maybe a better approach to saving a bunch of images at once?
**Edit:** I think what is happening, is the serializer is making the `byte[]` into a base64 string, which is then getting passed along to the stored proc as base64. I am then saving this base64 string into an Image field in SQL and reading it out as a `btye[]`. So I think I need to somehow get it from base64 to a `byte[]` before inserting it in my table?
**Edit:** I am starting to think my only option is to change the stored proc to just do 1 image at a time and not use XML and just pass in the `byte[]` as an `Image` type and wrap all the calls in a transaction. | As Gaidin suggested, base64 is the best option. It's the usual way of writing binary data to XML. You can use the following code :
```
public class ExampleImage
{
public int ID { get; set; }
public string Filename { get; set; }
[XmlIgnore]
public byte[] Content { get; set; }
[XmlElement("Content")]
public string ContentBase64
{
get { return Convert.ToBase64String(Content); }
set { Content = Convert.FromBase64String(value); }
}
}
```
(by the way, the `Serializable` attribute has no meaning for XML serialization) | Instead of serializing it to XML, I would serialize it to a byte[] and store that in varbinary(MAX) type field in your DB. | Serializing a object with an image to be saved to SQL database | [
"",
"c#",
"xml",
"serialization",
"sql-server-2000",
"binary-data",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.