Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have to automate something for the finance dpt. I've got an Excel file which I want to read using OleDb:
```
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=A_File.xls;Extended Properties=""HTML Import;IMEX=1;""";
using (OleDbConnection connection = new OleDbConnection())
{
using (DbCommand command = connection.CreateCommand())
{
connection.ConnectionString = connectionString;
connection.Open();
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
{
//raise exception if needed
}
command.CommandText = "SELECT * FROM [NameOfTheWorksheet$]";
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
//do something with the data
}
}
}
}
```
Normally the `connectionstring` would have an extended property "Excel 8.0", but the file can't be read that way because it seems to be an html file renamed to .xls.
when I copy the data from the xls to a new xls, I **can** read the new xls with the E.P. set to "Excel 8.0".
Yes, I can read the file by creating an instance of Excel, but I rather not..
Any idea how I can read the xls using OleDb without making manual changes to the xls or by playing with ranges in a instanciated Excel?
Regards,
Michel | I asked this same question on another forum and got the answer so I figured I'd share it here. As per this article: <http://ewbi.blogs.com/develops/2006/12/reading_html_ta.html>
Instead of using the sheetname, you must use the page title in the select statement without the $. SELECT \* FROM [HTMLPageTitle] | I've been searching so many solution, end up I found something really simple and easy -
to import XML file to Excel file, I tried to convert XML to HTML first, use -
<http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63>
then I found I could easily change my output file as .xls, instead of .html
```
//create the output stream
XmlTextWriter myWriter = new XmlTextWriter
("result.html", null);
```
then the output is perfect Excel file from my XML data file.
hope this will save ur work. | C# Excel file OLEDB read HTML IMPORT | [
"",
"c#",
".net",
"html",
"excel",
"oledb",
""
] |
Think about a table like this
```
ID Value
100 1
100 3
101 1
101 4
102 2
102 5
103 2
103 4
104 1
104 3
105 2
105 5
```
The problem is, if I give values 2 and 5 I should get 102 and 105 which both 102 and 105 are having values 2 and 5 at the same time or if I give values 1 and 3 I should get 100 and 104.
How can I do this with only one sql command? I need a query as light as possible.
and using UNION, INTERSECTION or NESTED SQLs, which one is faster, slower, heavier e.t.c?
Thanks in advance
Ergec | There's lots of solutions. Addition to the Jhonny's solution, you can use a join
```
SELECT DISTINCT t1.id
FROM table t1, table t2
WHERE t1.id = t2.id
AND t1.value = 2
AND t2.value = 5
```
OR use Intersect
```
SELECT id FROM table WHERE value = 2
INTERSECT
SELECT id FROM table WHERE value = 5
``` | Try something like this:
```
SELECT id
FROM test
WHERE
value in (2,5)
GROUP by id
HAVING count(*) = 2
```
If you want to test it, simple table for it (with no indexes!):
```
CREATE TABLE IF NOT EXISTS test (
id int(4) NOT NULL,
`value` int(4) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO test (id, value) VALUES
(100, 1),
(100, 3),
(101, 1),
(101, 4),
(102, 2),
(102, 5),
(103, 2),
(103, 4),
(104, 1),
(104, 3),
(105, 2),
(105, 5);
```
I had a very similar question a few days ago. see [MySQL - Find rows matching all rows from joined table](https://stackoverflow.com/questions/1242223/mysql-find-rows-matching-all-rows-from-joined-table) | Finding ID having all values (mySQL, SQL) | [
"",
"sql",
"mysql",
""
] |
When debugging my project in Visual Studio 2008, my Settings.settings file keeps getting reset between builds. Is there a way to prevent this from happening?
Thanks. | Okay, I found out the answer I was really looking for. Basically, you need to call LocalFileSettingsProvider.Upgrade. However, since I will be deploying using ClickOnce, it will do it for you automatically.
---
Q: Okay, but how do I know when to call Upgrade?
A: Good question. In Clickonce, when you install a new version of your application, ApplicationSettingsBase will detect it and automatically upgrade settings for you at the point settings are loaded. In non-Clickonce cases, there is no automatic upgrade - you have to call Upgrade yourself. Here is one idea for determining when to call Upgrade:
Have a boolean setting called CallUpgrade and give it a default value of true. When your app starts up, you can do something like:
```
if (Properties.Settings.Value.CallUpgrade)
{
Properties.Settings.Value.Upgrade();
Properties.Settings.Value.CallUpgrade = false;
}
```
This will ensure that Upgrade() is called only the first time the application runs after a new version is deployed.
REF: <http://blogs.msdn.com/rprabhu/articles/433979.aspx> | I believe Settings.settings files are saved based on the current version number, basically as a "feature" where settings are not saved between differing versions of the same program on a machine. Assuming you're incrementing the version number automatically when compiling (1.0.\* in AssemblyInfo.cs), you'll be resetting your settings everytime you compile a new version.
To correct this, the best course would be to serialize your own settings file to the Application Data directory. | Settings.settings File Keeps Getting Reset | [
"",
"c#",
"visual-studio-2008",
""
] |
I am programing under windows, c++, mfc
How can I know disk's format by path such as "c:\".
Does windows provide such APIs? | The Win32API function ::GetVolumeInformation is what you are looking for.
From MSDN:
[GetVolumeInformation Function](http://msdn.microsoft.com/en-us/library/aa364993(VS.85).aspx)
```
BOOL WINAPI GetVolumeInformation(
__in_opt LPCTSTR lpRootPathName,
__out LPTSTR lpVolumeNameBuffer,
__in DWORD nVolumeNameSize,
__out_opt LPDWORD lpVolumeSerialNumber,
__out_opt LPDWORD lpMaximumComponentLength,
__out_opt LPDWORD lpFileSystemFlags,
__out LPTSTR lpFileSystemNameBuffer, // Here
__in DWORD nFileSystemNameSize
);
```
Example:
```
TCHAR fs [MAX_PATH+1];
::GetVolumeInformation(_T("C:\\"), NULL, 0, NULL, NULL, NULL, &fs, MAX_PATH+1);
// Result is in (TCHAR*) fs
``` | Yes it is GetVolumeInformation.
```
TCHAR szVolumeName[100] = "";
TCHAR szFileSystemName[10] = "";
DWORD dwSerialNumber = 0;
DWORD dwMaxFileNameLength = 0;
DWORD dwFileSystemFlags = 0;
if(::GetVolumeInformation("c:\\",
szVolumeName,
sizeof(szVolumeName),
&dwSerialNumber,
&dwMaxFileNameLength,
&dwFileSystemFlags,
szFileSystemName,
sizeof(szFileSystemName)) == TRUE)
{
cout << "Volume name = " << szVolumeName << endl
<< "Serial number = " << dwSerialNumber << endl
<< "Max. filename length = " << dwMaxFileNameLength
<< endl
<< "File system flags = $" << hex << dwFileSystemFlags
<< endl
<< "File system name = " << szFileSystemName << endl;
}
``` | How to know a certain disk's format(is FAT32 or NTFS) | [
"",
"c++",
"winapi",
"mfc",
""
] |
I'm not very good at explaining in english but i'll give it a go. Hope you understand.
In php i have this script that fetches an URL and displays the content. So far so good. The content is shown like this:
eg.
site.php?url=<http://google.com>
But WHEN i click on something in the page, eg. google.com, then my site disappears and the user is browsed to google.com
How do i do that when they click on a link, they should stay in my site and only the URL parameter should change.
Thanks!
I hope u understood me, i don't write english very well... | You need to go through all of the links on the page, replacing them with links to your site, so that
```
<a href="http://www.something.com">Some Link</a>
```
...is turned into:
```
<a href="http://www.yoursite.com/site.php?url=http://www.something.com">Some Link</a>
```
Note that you'll have to all kinds of fancy URL encoding and escaping to make it work correctly. Have fun! | I hope this is relevant: Another technique would be to open the related site in, [**gasp**], an iframe. That way any links clicked in the iframe would stay in its own frame, much like how the digg bar or facebook outbound links work, but you could still maintain control of the surrounding content. | underlinks also | [
"",
"php",
"hyperlink",
""
] |
I'm trying to communicate between WCF hosted in Windows Service and my service GUI. The problem is when I'm trying to execute OperationContract method I'm getting
> "The ChannelDispatcher at
> 'net.tcp://localhost:7771/MyService'
> with contract(s) '"IContract"' is
> unable to open its IChannelListener."
My app.conf looks like that:
```
<configuration>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTcpBinding">
<security>
<transport protectionLevel="EncryptAndSign" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:7772/MyService" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MyServiceBehavior"
name="MyService.Service">
<endpoint address="net.tcp://localhost:7771/MyService" binding="netTcpBinding"
bindingConfiguration="netTcpBinding" name="netTcp" contract="MyService.IContract" />
</service>
</services>
</system.serviceModel>
```
Port 7771 is listening (checked using netstat) and svcutil is able to generate configs for me.
Any suggestions would be appreciated.
---
Stack trace from exception
> ```
> Server stack trace:
> at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
> at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
> at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
> at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
> at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
> at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
> ```
---
There's one inner exeption (but not under Exeption.InnerExeption but under Exeption.Detail.InnerExeption - ToString() method doesn't show that)
> A registration already exists for URI 'net.tcp://localhost:7771/MyService'.
But my service have specified this URI only in app.config file nowhere else. In entire solution this URI apears in server once and client once. | I solved it :D
Here's the explanaition of the problem:
First BAD code:
```
namespace WCFServer
{
public class Program : IWCFService
{
private ServiceHost host;
static void Main(string[] args)
{
new Program();
}
public Program()
{
host = new ServiceHost(typeof(Program));
host.Open();
Console.WriteLine("Server Started!");
Console.ReadKey();
}
#region IWCFService Members
public int CheckHealth(int id)
{
return (1);
}
#endregion
}
}
```
As you can see the service contract is implemented in class hosting the service. This caused the whole error thing (maybe typeof() runs a constructor, i don't know I'm open to constructive input in this matter).
The GOOD code:
```
namespace WCFServer
{
public class Program
{
private ServiceHost host;
static void Main(string[] args)
{
new Program();
}
public Program()
{
host = new ServiceHost(typeof(WCF));
host.Open();
Console.WriteLine("Server Started!");
Console.ReadKey();
}
}
public class WCF : IWCFService
{
#region IWCFService Members
public int CheckHealth(int id)
{
return (1);
}
#endregion
}
}
```
Service Contract for both files:
```
[ServiceContract]
public interface IWCFService
{
[OperationContract]
int CheckHealth(int id);
}
```
App.config
```
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WCFBehavior" />
</serviceBehaviors>
</behaviors>
<bindings>
<netTcpBinding>
<binding name="tcpBinding">
<security>
<transport>
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
</security>
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="WCFServer.WCF">
<endpoint address="net.tcp://localhost:1111/TcpIHostMonitor" binding="netTcpBinding"
bindingConfiguration="tcpBinding" name="netTcpEndpoint" contract="WCFServer.IWCFService" />
</service>
</services>
</system.serviceModel>
``` | With this type of exception it's the Inner exception that has the information that is useful to diagnose the problem. This is a rather generic error that could be caused by a bunch of different things. | How to solve "The ChannelDispatcher is unable to open its IChannelListener" error? | [
"",
"c#",
"wcf",
"interprocess",
"net.tcp",
""
] |
I have a problem which I believe is the classic master/worker pattern, and I'm seeking advice on implementation. Here's what I currently am thinking about the problem:
There's a global "queue" of some sort, and it is a central place where "the work to be done" is kept. Presumably this queue will be managed by a kind of "master" object. Threads will be spawned to go find work to do, and when they find work to do, they'll tell the master thing (whatever that is) to "add this to the queue of work to be done".
The master, perhaps on an interval, will spawn other threads that actually perform the work to be done. Once a thread completes its work, I'd like it to notify the master that the work is finished. Then, the master can remove this work from the queue.
I've done a fair amount of thread programming in Java in the past, but it's all been prior to JDK 1.5 and consequently I am not familiar with the appropriate new APIs for handling this case. I understand that JDK7 will have fork-join, and that that might be a solution for me, but I am not able to use an early-access product in this project.
The problems, as I see them, are:
1) how to have the "threads doing the work" communicate back to the master telling them that their work is complete and that the master can now remove the work from the queue
2) how to efficiently have the master guarantee that work is only ever scheduled once. For example, let's say this queue has a million items, and it wants to tell a worker to "go do these 100 things". What's the most efficient way of guaranteeing that when it schedules work to the next worker, it gets "the next 100 things" and not "the 100 things I've already scheduled"?
3) choosing an appropriate data structure for the queue. My thinking here is that the "threads finding work to do" could potentially find the same work to do more than once, and they'd send a message to the master saying "here's work", and the master would realize that the work has already been scheduled and consequently should ignore the message. I want to ensure that I choose the right data structure such that this computation is as cheap as possible.
Traditionally, I would have done this in a database, in sort of a finite-state-machine manner, working "tasks" through from start to complete. However, in this problem, I don't want to use a database because of the high volume and volatility of the queue. In addition, I'd like to keep this as light-weight as possible. I don't want to use any app server if that can be avoided.
It is quite likely that this problem I'm describing is a common problem with a well-known name and accepted set of solutions, but I, with my lowly non-CS degree, do not know what this is called (i.e. please be gentle).
Thanks for any and all pointers. | As far as I understand your requirements, you need [ExecutorService](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html). ExecutorService have
```
submit(Callable task)
```
method which return value is [Future](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html). Future is a blocking way to communicate back from worker to master. You could easily expand this mechanism to work is asynchronous manner. And yes, ExecutorService also maintaining work queue like ThreadPoolExecutor. So you don't need to bother about scheduling, in most cases. java.util.concurrent package already have efficient implementations of thread safe queue (ConcurrentLinked queue - nonblocking, and LinkedBlockedQueue - blocking). | Check out [java.util.concurrent](http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html) in the Java library.
Depending on your application it might be as simple as cobbling together some blocking queue and a ThreadPoolExecutor.
Also, the book [*Java Concurrency in Practice*](http://jcip.net/) by Brian Goetz might be helpful. | Patterns/Principles for thread-safe queues and "master/worker" program in Java | [
"",
"java",
"algorithm",
"multithreading",
"data-structures",
"queue",
""
] |
So - if [there isn't particular reason](https://stackoverflow.com/questions/294216/why-does-c-forbid-generic-attribute-types) why there isn't generic attributes,
I'm wondering - maybe they will be implemented?
Those would be great for ASP.NET MVC action filters. | I haven't seen any evidence of this in the [4.0 spec](http://download.microsoft.com/download/7/E/6/7E6A548C-9C20-4C80-B3B8-860FAF20887A/CSharp%204.0%20Specification.doc)... so I believe the answer is "no". | C# 4 specification does not mention generics in attributes. | Will there be generic attributes in C# 4? | [
"",
"c#",
"generics",
"attributes",
""
] |
Basic JavaScript question: Since there is no hard limit for arrays as the case with Java (i.e. [IndexOutOfBoundsException](https://docs.oracle.com/javase/8/docs/api/java/lang/IndexOutOfBoundsException.html)), what is the use of the declaration where we specify the length property?
```
var a = new Array(10);
```
I know it predefines the length and puts "undefined" into those empty spots. Is that reason enough for having it? | There are many perceived benefits of declaring an array size, but I think the majority of the perceived benefits are just FUD being passed around.
**Better performance!/It's faster!**
As far as I can tell the difference between pre-allocating and dynamic allocation is negligible.
More interestingly, the spec does **not** state that the array should be set to a pre-allocated length!
From Section 15.4.2.2 [ECMA-262](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf "ECMAScript specification (PDF)"):
> If the argument *len* is a Number and ToUint32(*len*) is equal to *len*, then the **length** property of the newly constructed object is set to ToUint32(*len*). If the argument *len* is a Number and ToUint32(*len*) is not equal to *len*, a **RangeError** exception is thrown.
An unscientific for-fun test case is here: <http://jsbin.com/izini>
**It makes for more understandable code!**
Personally, I disagree.
Consider the javascript you have written in the past, and consider code you may have to write in the future. I can't think of a single time where I've needed to specify a static limit on one of my arrays. I'd also argue that the potential problems of limiting arrays in javascript highly outweigh the benefits caused by letting people know what you were thinking with no actual checks behind it. Lets weigh the pros and cons...
Pros:
1. It will be easier for them to understand what you intended the code to do.
2. They will be able to find the bugs caused by your assumption later on (tongue firmly in cheek)
Cons:
1. Quick glances can easily confuse "new Array(10)" with "new Array('10')" which do entirely different things!
2. You are imposing an arbitrary limit on code with no normal length limit causing you to write lots of boiler plate code to check and maintain the limit.
3. You are imposing an arbitrary limit on code which could probably have been generalized to work with any length of values.
4. You're making an assumption about how people will read your code while assuming that the alternative would be less confusing.
You may as well have written:
```
//I assume this array will always be length 10
var arr = new Array();
```
In the above case the comment might even be preferable. The explicit declaration of intent can avoid any confusion not used to using the constructor as a declaration of intent.
**Fine then.. why do you think it's even there then?**
Convenience. When they were writing the spec I think they realized two things.
1. This sort of assignment would be something developers coming from similar languages would be used to.
2. Implementations of ECMAScript might potentially use it for performance gains.
So they put it in there.
The spec only defines the use of the parameter, not how it should be implemented. | Performance on the V8 JavaScript engine.
By doing:
```
var arr = []; arr.length = 1000;
```
V8 will preallocate the required memory for the array and maintain/set the array's `Hidden Class` to *compact SMI* (Small Int, 31 bits unsigned) *array*. However, this is not true when the desired length is too big, which results in the HC being set to *sparse array* (i.e., map).
Try the following link on Chrome: <http://jsperf.com/0-fill-n-size-array>
I've included an extra test case without the array length definition so you can tell the actual performance difference.
Related info: <http://www.youtube.com/watch?v=UJPdhx5zTaw> | Use of JavaScript new Array(n) Declaration | [
"",
"javascript",
""
] |
I am currently trying to wrap my mind around Java EE 5. What I'd like to do is create a sample application that
* offers a simple stateless EJB (e. g. a simple calulator with an add() method)
* expose this add method as a webservice
* consume this webservice from another EJB
The first two steps are easy and I can deploy and test this bean to Glassfish v2.1 already and test it with a standalone client:
```
@WebService
@Stateless
public class CalculatorWS {
@WebMethod
public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {
int k = i + j;
return k;
}
}
```
What I do not get however, is how to consume a webservice like this from a second EJB. While not strictly useful in this example, I will have to write some EJBs soon that will wrap external webservices as to keep my internal clients from having to deal with those external resources.
From what I understand, I should be able to have the container inject me a webservice into a field of my EJB? I did not find an example for this, however. I'd welcome any hints to tutorials covering this - or even better an example right here :-)
For what it's worth, I am using Eclipse 3.5. | From the official Java EE tutorial
[Consuming a Web service](http://java.sun.com/javaee/5/docs/tutorial/doc/bnayn.html#bnayx) | The Web Service client isn't really EJB specific. So I think you'd use JAX-WS client techniques, your EJB environment being a managed envirnment (JNDI etc all nicely available).
I know you're not using WebSphere but I hope the techniques explained [here](http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/twbs_devwbsjaxwsclient.html) are generally applicable. | How to consume a webservice from an EJB | [
"",
"java",
"web-services",
"dependency-injection",
"jakarta-ee",
"ejb-3.0",
""
] |
I have a small system consisting of a .net client and a java web service.
The .net client inserts an object into the database, and then calls the web service. The web service tries to retrieve this object using hibernate. First time it works fine, but every other time it says that there is no object with the given identifier.
I have checked the database manually and the row is indeed there! (I debugged the web service and checked for the row even before a session was opened).
**SOLUTION**
Added this to the hibernate config file
```
<property name="connection.isolation">1</property>
```
Here's what I've tried so far:
1. The second level cache is disabled
2. Added .setCacheMode(CacheMode.REFRESH)
Here's the failing code:
```
Session session = Program.HibernateUtil.getSessionFactory().openSession();
try
{
return (Alert)session.load(Alert.class, id);
} ...
``` | It looks like the second level cache (the one associated with the session factory) should be disabled so the only other thing I can suggest is to explicitly clear the cache with the call:
```
sessionFactory.evict(Alert.class)
```
**Note:** read the comments for the full answer. | Firstly, don't use `Session.load()`, use `Session.get()`. `load()` should only be used in very particular situations, and this ain't one of them.
Secondly, are you performing both operations within the same Session? If so, Hibernate will cache the entity after the first operation. There's no way to stop it doing this. However, you can use `evict()` on the Session to forceably kick the entity out of the session cache. | Hibernate doesn't notice database updates made from other source | [
"",
"java",
"hibernate",
"caching",
""
] |
when i try to launch my c# application on another computer than it was developed i get the following error message:
> System.IO.FileLoadException: Could not load file or assembly 'Widgets3D, Version=1.0.3511.25568, Culture=neutral, PublicKeyToken=null' or one of its dependencies. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)
>
> File name: 'Widgets3D, Version=1.0.3511.25568, Culture=neutral, PublicKeyToken=null' ---> System.Runtime.InteropServices.COMException (0x800736B1): This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1)
i checked with dependency walker and process monitor but couldnt find any missing DLLs.
especially the one mentioned in the error Widgets3D.dll is there!
both PCs are up to date with the latest XP service pack and updates. the application works on many PCs here. there is just this one which is making the problem.
EDIT:
as suggested i tried to regsvr32 the missing dll, but that gives me this error:
> LoadLibrary("./Widgets3D.dll") failed - This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
thanks! | just in case you are interested. we found the solution to the problem to be a recent
security patch for VC KB971090
uninstalling this patch and rebuilding the DLLs solved the issue.
there are quite a few topics on this:
<https://stackoverflow.com/search?q=KB971090> | Reading that exception, here is the important part:
> System.Runtime.InteropServices.COMException
That's not a .Net assembly. It's a COM dll, and it needs to be registered. | c# application does not start on another computer | [
"",
"c#",
"dll",
"crash",
""
] |
When I read certain JPG files, colors are flattened. Here is a simple example that reads a jpg and just writes the same image to another file.
```
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class JPegReadTest {
public static void main(String[] args) {
if (args.length == 2) {
try {
BufferedImage src = ImageIO.read(new File(args[0]));
ImageIO.write(src, "jpg", new File(args[1]));
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("Usage: java JPegReadTest src dest");
}
}
}
```
If you try this with for example <http://www.flickr.com/photos/visualpanic/233508614/sizes/l/> , the colors of the destination image differ from the source file. Why is that? How to fix it?
Also tried saving the image as png, but the colors are bland in it too (so assuming color info is not read properly). | It could be several reasons.
1. JPEG color data is often stored as YCrCb instead of RGB, although conversions should be mostly unnoticeable.
2. JPEG often has an embedded color profile, but many applications do not understand this and simply ignore it (in which case, your output file might be missing the color profile).
3. Gamma value could be reset or missing after Java mangles it.
I didn't actually try your example... could you please post both before and after files? Without actually being able to examine the result file, it's hard to tell if this extra data is there or not.
**Edit:** Yeah, it's clear that your original and converted images have different color profiles. Java stripped out the original's color profile and used generic sRGB instead. They look the same to us on Windows with Firefox and assorted programs because these programs don't use the color profile when renderer. However, on your Mac, Mac actually supports these color profiles (cue debate over Macs for graphics, etc.) and so they render differently. I don't have a Mac handy, but I suspect that if you open the files in Photoshop on any platform, you'll see the difference. | Perhaps your source image has an assigned color profile with a gamut wider than sRGB (like Adobe RGB), and your load/save cycle isn't preserving the colorspace information? With no color profile, your viewer will assume sRGB, and the compressed gamut will make everything look "blah". If you have exiftool,
```
exiftool -ProfileDescription filename.jpg
```
is a quick way to verify the color profiles on your source and output images. | Why Java ImageIO flattens JPEG colors | [
"",
"java",
"jpeg",
"javax.imageio",
""
] |
I was checking the behavior of dynamic\_cast and found that when it fails, std::bad\_cast exception is thrown only if the destination is a reference type. If the destination is a pointer type then no exception is thrown from the cast. This is my sample code:
```
class A
{
public:
virtual ~A()
{
}
};
class B : public A
{
};
int main()
{
A* p = new A;
//Using reference
try
{
B& b = dynamic_cast<B&>(*p);
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast\n";
}
//Using pointer
try
{
B* pB = dynamic_cast<B*>(p);
if( pB == NULL)
{
std::cout<<"NULL Pointer\n";
}
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast\n";
}
return 0;
}
```
Output is "Caught bad cast" and "NULL pointer". Code is compiled using VS2008. Is this the correct behavior ? If yes, then why there is a difference? | Yes, this is correct behaviour. The reason is that you can have a null pointer, but not a null reference - any reference has to be bound to an object.
So when dynamic\_cast for a pointer type fails it returns a null pointer and the caller can check for that, but when it fails for a reference type it can't return a null reference, so an exception is the only reasonable way to signal a problem. | See the C++ Standard, section 5.2.7/9:
> 9 The value of a failed cast to
> pointer type is the null pointer value
> of the required result type. A failed
> cast to reference type throws bad\_cast
> (18.5.2).
As to why - these are Stroustrup's words from the D & E book, section 14.2.2:
> I use a reference cast when I want an
> assumption about a reference type
> checked and consider it a failure for
> my assumption to be wrong. If instead
> I want to select among plausible
> alternatives, I use a pointer cast and
> test the result. | Difference in behavior while using dynamic_cast with reference and pointers | [
"",
"c++",
"casting",
"dynamic-cast",
""
] |
I'll preface this question by stating that I'm using Oracle 10g Enterprise edition and I'm relatively new to Oracle.
I've got a table with the following schema:
```
ID integer (pk) -- unique index
PERSON_ID integer (fk) -- b-tree index
NAME_PART nvarchar -- b-tree index
NAME_PART_ID integer (fk) -- bitmap index
```
The `PERSON_ID` is the foreign key for the unique id of a person record. The `NAME_PART_ID` is the foreign key of a lookup table with static values like "First Name", "Middle Name", "Last Name", etc. The point of the table is to store individual parts of people's names separately. Every person record has at least a first name. When trying to pull the data out, I first considered using joins, like so:
```
select
first_name.person_id,
first_name.name_part,
middle_name.name_part,
last_name.name_part
from
NAME_PARTS first_name
left join
NAME_PARTS middle_name
on first_name.person_id = middle_name.person_id
left join
NAME_PARTS last_name
on first_name.person_id = last_name.person_id
where
first_name.name_part_id = 1
and middle_name.name_part_id = 2
and last_name.name_part_id = 3;
```
But the table has tens of millions of records, and the bitmap index for the `NAME_PART_ID` column isn't being used. The explain plan indicates that the optimizer is using full table scans and hash joins to retrieve the data.
Any suggestions?
EDIT: The reason the table was designed this way was because the database is used across several different cultures, each of which has different conventions for how individuals are named (e.g. in some middle-eastern cultures, individuals usually have a first name, then their father's name, then his father's name, etc). It is difficult to create one table with multiple columns that account for all of the cultural differences. | Given that you're essentially doing a full table scan anyway (as your query is extracting all data from this table, excluding the few rows that wouldn't have name parts that were first, middle or last), you may want to consider writing the query so that it just returns the data in a slightly different format, such as:
```
SELECT person_id
, name_part_id
, name_part
FROM NAME_PART
WHERE name_part_id IN (1, 2, 3)
ORDER BY person_id
, name_part_id;
```
Of course, you'll end up with 3 rows instead of one for each name, but it may be trivial for your client code to roll these together. You can also roll the 3 rows up into one by using decode, group by and max:
```
SELECT person_id
, max(decode(name_part_id, 1, name_part, null)) first
, max(decode(name_part_id, 2, name_part, null)) middle
, max(decode(name_part_id, 3, name_part, null)) last
FROM NAME_PART
WHERE name_part_id IN (1, 2, 3)
GROUP BY person_id
ORDER BY person_id;
```
This will produce results identical to your original query. Both versions will only scan the table once (with a sort), instead of dealing with the 3-way join. If you made the table an index-organized table on the person\_id index, you'd save the sort step.
I ran a test with a table with 56,150 persons, and here's a rundown of the results:
Original query:
```
Execution Plan
----------------------------------------------------------
------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)|
------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 113K| 11M| | 1364 (2)|
|* 1 | HASH JOIN | | 113K| 11M| 2528K| 1364 (2)|
|* 2 | TABLE ACCESS FULL | NAME_PART | 56150 | 1864K| | 229 (3)|
|* 3 | HASH JOIN | | 79792 | 5298K| 2528K| 706 (2)|
|* 4 | TABLE ACCESS FULL| NAME_PART | 56150 | 1864K| | 229 (3)|
|* 5 | TABLE ACCESS FULL| NAME_PART | 56150 | 1864K| | 229 (3)|
------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - access("FIRST_NAME"."PERSON_ID"="LAST_NAME"."PERSON_ID")
2 - filter("LAST_NAME"."NAME_PART_ID"=3)
3 - access("FIRST_NAME"."PERSON_ID"="MIDDLE_NAME"."PERSON_ID")
4 - filter("FIRST_NAME"."NAME_PART_ID"=1)
5 - filter("MIDDLE_NAME"."NAME_PART_ID"=2)
Statistics
----------------------------------------------------------
0 recursive calls
0 db block gets
6740 consistent gets
0 physical reads
0 redo size
5298174 bytes sent via SQL*Net to client
26435 bytes received via SQL*Net from client
3745 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
56150 rows processed
```
My query #1 (3 rows/person):
```
Execution Plan
----------------------------------------------------------
-----------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)|
-----------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 168K| 5593K| | 1776 (2)|
| 1 | SORT ORDER BY | | 168K| 5593K| 14M| 1776 (2)|
|* 2 | TABLE ACCESS FULL| NAME_PART | 168K| 5593K| | 230 (3)|
-----------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("NAME_PART_ID"=1 OR "NAME_PART_ID"=2 OR "NAME_PART_ID"=3)
Statistics
----------------------------------------------------------
1 recursive calls
0 db block gets
1005 consistent gets
0 physical reads
0 redo size
3799794 bytes sent via SQL*Net to client
78837 bytes received via SQL*Net from client
11231 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
168450 rows processed
```
My query #2 (1 row/person):
```
Execution Plan
----------------------------------------------------------
-----------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)|
-----------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 56150 | 1864K| | 1115 (3)|
| 1 | SORT GROUP BY | | 56150 | 1864K| 9728K| 1115 (3)|
|* 2 | TABLE ACCESS FULL| NAME_PART | 168K| 5593K| | 230 (3)|
-----------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("NAME_PART_ID"=1 OR "NAME_PART_ID"=2 OR "NAME_PART_ID"=3)
Statistics
----------------------------------------------------------
1 recursive calls
0 db block gets
1005 consistent gets
0 physical reads
0 redo size
5298159 bytes sent via SQL*Net to client
26435 bytes received via SQL*Net from client
3745 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
56150 rows processed
```
Turns out, you can squeeze it a bit faster still; I tried to avoid the sort by adding an index hint to force the use of the person\_id index. I managed to knock off another 10%, but it still looks like it's sorting:
```
SELECT /*+ index(name_part,NAME_PART_person_id) */ person_id
, max(decode(name_part_id, 1, name_part)) first
, max(decode(name_part_id, 2, name_part)) middle
, max(decode(name_part_id, 3, name_part)) last
FROM name_part
WHERE name_part_id IN (1, 2, 3)
GROUP BY person_id
ORDER BY person_id;
Execution Plan
----------------------------------------------------------
-----------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)|
-----------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 56150 | 1864K| | 3385 (1)|
| 1 | SORT GROUP BY | | 56150 | 1864K| 9728K| 3385 (1)|
| 2 | INLIST ITERATOR | | | | | |
| 3 | TABLE ACCESS BY INDEX ROWID | NAME_PART | 168K| 5593K| | 2500 (1)|
| 4 | BITMAP CONVERSION TO ROWIDS| | | | | |
|* 5 | BITMAP INDEX SINGLE VALUE | NAME_PART_NAME_PART_ID| | | | |
-----------------------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
5 - access("NAME_PART_ID"=1 OR "NAME_PART_ID"=2 OR "NAME_PART_ID"=3)
Statistics
----------------------------------------------------------
1 recursive calls
0 db block gets
971 consistent gets
0 physical reads
0 redo size
5298159 bytes sent via SQL*Net to client
26435 bytes received via SQL*Net from client
3745 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
56150 rows processed
```
However, the plans above are all based on the assumption that you're selecting from the entire table. If you constrain the results based on person\_id (e.g., person\_id between 55968 and 56000), it turns out that your original query with the hash joins is the fastest (27 vs. 106 consistent gets for the constraint I specified).
On the THIRD hand, if the queries above are being used to populate a GUI that uses a cursor to scroll over the result set (such that you would only see the first N rows of the result set initially - reproduced here by adding a "and rowcount < 50" predicate), my versions of the query once again become fast - very fast (4 consistent gets vs. 417).
The moral of the story is that it really depends exactly how you're accessing the data. Queries that work well on the entire result set may be worse when applied against different subsets. | Since you don't filter your tables in any way, the optimizer is probably right, `HASH JOIN` is the best way to join the unfiltered tables.
A bitmap index won't help you much in this case.
It's good for making `OR`'s and `AND`'s on multiple low-cardinality columns, not for pure filtering on a single column.
For this, a full table scan is almost always better.
Note that this is not the best design. I'd rather add the columns `first_name`, `last_name` and `middle_name` into `person`, building an index on each of the columns and making them NULLable.
In this case you have the same table as in your design, but without a table.
The indexes hold the name and the `rowid` just as well as a table does, and the join on rowid is much more efficient.
**Update:**
Myself being a member of a culture that uses father's name as a part of personal name, I can say that using three fields is enough for most cases.
One field for the family name, one field for a given name and one field for everything in between (without further specialization) is quite a decent way to handle names.
Just rely on your users. In the modern world, almost everyone knows how to fit their name into this schema.
For instance:
```
Family name: Picasso
Given name: Pablo
Middle name: Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y
```
`P. S.` Did you know that close friends just called him `PABLO~1` ? | Help optimizing an Oracle query | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
I have a class library, which I want to expose to the outside world as a WCF service. My class contains abstract classes, normal classes, enums etc.
I simple wnat that people can make a "service reference" of my class library in their project and they start using it.
How do I acheive this? | If you haven't finished this yet, you can save yourself from a big mistake by not starting.
A class library is designed to be a class library. A service is designed to be a service. They are two different things with different goals.
For example, you may have defined an enum, and an EventArgs-derived class that has a property of that enum type, and an event handler delegate that takes that EventArgs type, and you may have one or more classes that expose events that use that delegate type.
None of those things make any sense to expose in a service!
Instead, what you should do is to design your service to expose the *functionality* you want exposed. In order to do that, the service will, of course, use your class library.
One thing different between a class library and a service is that a service should be designed to be usable across platforms. Consider what happens when a Java client consumes your service: it will have a proxy class that corresponds ot the operations exposed by your service. Those proxy methods will have parameters of primitive types, and of proxy types that match the structure of the data passed to and from your service.
The Java client will obviously not use the same .NET types that your server-side operations use!
The default way to build a .NET client works the exact same way - through proxy classes. Your question suggests that you expect that exposing the class library will export the actual classes to the client. That is not the case. If you decide to couple the client to the exact .NET classes used by the server, then the clients will need to have the server-side assembly, just as though the clients were using a normal class library. | Classes and enums can be exposed through WCF. Abstract classes however will be a problem, but it doesn't make sense to expose them as a service anyway.
For enumerations, you will have to add the `[EnumMember]` attribute, for example:
```
public enum Sex
{
[EnumMember]
Unknown,
[EnumMember]
Male,
[EnumMember]
Female
}
```
The whole subject of WCF is a bit too broad to cover it all here though. Just see what happens and if you run into trouble, ask more specific questions. | Expose a Class Library as a WCF Service | [
"",
"c#",
"wcf",
""
] |
I'm using OleDb to read from an excel workbook with many sheets.
I need to read the sheet names, but I need them in the order they are defined in the spreadsheet; so If I have a file that looks like this;
```
|_____|_____|____|____|____|____|____|____|____|
|_____|_____|____|____|____|____|____|____|____|
|_____|_____|____|____|____|____|____|____|____|
\__GERMANY__/\__UK__/\__IRELAND__/
```
Then I need to get the dictionary
```
1="GERMANY",
2="UK",
3="IRELAND"
```
I've tried using `OleDbConnection.GetOleDbSchemaTable()`, and that gives me the list of names, but it alphabetically sorts them. The alpha-sort means I don't know which sheet number a particular name corresponds to. So I get;
```
GERMANY, IRELAND, UK
```
which has changed the order of `UK` and `IRELAND`.
The reason I need it to be sorted is that I have to let the user choose a range of data by name or index; they can ask for 'all the data from GERMANY to IRELAND' or 'data from sheet 1 to sheet 3'.
Any ideas would be greatly appreciated.
if I could use the office interop classes, this would be straightforward. Unfortunately, I can't because the interop classes don't work reliably in non-interactive environments such as windows services and ASP.NET sites, so I needed to use OLEDB. | Can't find this in actual MSDN documentation, but a moderator in the forums said
> I am afraid that OLEDB does not preserve the sheet order as they were in Excel
[Excel Sheet Names in Sheet Order](http://social.msdn.microsoft.com/Forums/en/adodotnetdataproviders/thread/2f459200-deef-4131-be8a-1b67a41efb97)
Seems like this would be a common enough requirement that there would be a decent workaround. | Can you not just loop through the sheets from 0 to Count of names -1? that way you should get them in the correct order.
**Edit**
I noticed through the comments that there are a lot of concerns about using the Interop classes to retrieve the sheet names. Therefore here is an example using OLEDB to retrieve them:
```
/// <summary>
/// This method retrieves the excel sheet names from
/// an excel workbook.
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns>String[]</returns>
private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
// Connection String. Change the excel file to the file you
// will search.
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(connString);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
// Loop through all of the sheets if you want too...
for(int j=0; j < excelSheets.Length; j++)
{
// Query each excel sheet.
}
return excelSheets;
}
catch(Exception ex)
{
return null;
}
finally
{
// Clean up.
if(objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if(dt != null)
{
dt.Dispose();
}
}
}
```
Extracted from [Article](http://www.codeproject.com/KB/aspnet/getsheetnames.aspx) on the CodeProject. | Using Excel OleDb to get sheet names IN SHEET ORDER | [
"",
"c#",
"excel",
"oledb",
"server-side",
""
] |
In order to better balance out a page I am working on I would like to find a way to increase the top margin of a DIV depending on the screen resolution. What is my best way to set these dimensions with jQuery or Javascript? | To get screen resolution in JS use `screen` object
```
screen.height;
screen.width;
```
Based on that values you can calculate your margin to whatever suits you. | Here is an example on how to center an object vertically with jQuery:
```
var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2 + 'px');
```
But you could easily change that to whatever your needs are. | jQuery Screen Resolution Height Adjustment | [
"",
"javascript",
"jquery",
"screen",
"resolution",
"margins",
""
] |
I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.
Is it possible to attach some sort of "isvisible" event handler to arbitrary divs and have certain code run when they the div is made visible?
I would like something like the following pseudocode:
```
$(function() {
$('#contentDiv').isvisible(function() {
alert("do something");
});
});
```
The alert("do something") code should not fire until the contentDiv is actually made visible.
Thanks. | You could always add to the original [.show()](http://api.jquery.com/show/) method so you don't have to trigger events every time you show something or if you need it to work with legacy code:
### Jquery extension:
```
jQuery(function($) {
var _oldShow = $.fn.show;
$.fn.show = function(speed, oldCallback) {
return $(this).each(function() {
var obj = $(this),
newCallback = function() {
if ($.isFunction(oldCallback)) {
oldCallback.apply(obj);
}
obj.trigger('afterShow');
};
// you can trigger a before show if you want
obj.trigger('beforeShow');
// now use the old function to show the element passing the new callback
_oldShow.apply(obj, [speed, newCallback]);
});
}
});
```
### Usage example:
```
jQuery(function($) {
$('#test')
.bind('beforeShow', function() {
alert('beforeShow');
})
.bind('afterShow', function() {
alert('afterShow');
})
.show(1000, function() {
alert('in show callback');
})
.show();
});
```
This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.
You could also create another method so you don't have to override the original .show() method. | The problem is being addressed by [DOM mutation observers](https://developer.mozilla.org/en-US/docs/DOM/MutationObserver). They allow you to bind an observer (a function) to events of changing content, text or attributes of dom elements.
With the release of IE11, all major browsers support this feature, check <http://caniuse.com/mutationobserver>
The example code is a follows:
```
$(function() {
$('#show').click(function() {
$('#testdiv').show();
});
var observer = new MutationObserver(function(mutations) {
alert('Attributes changed!');
});
var target = document.querySelector('#testdiv');
observer.observe(target, {
attributes: true
});
});
```
```
<div id="testdiv" style="display:none;">hidden</div>
<button id="show">Show hidden div</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
``` | jQuery event to trigger action when a div is made visible | [
"",
"javascript",
"jquery",
""
] |
Does anyone know how I can write a Javacript function which returns true if the browser's Javascript engine has been idle for a certain amount of time?
I am happy to use mootools / jQuery etc if easier, with a slight preference for mootools.
EDIT:
My actual problem: I'm making a call to a 3rd party's API. The call returns immediately but the actual work it does to the DOM goes on for some time (> 10 seconds in many cases). I want some code of mine to run as soon as the DOM work is complete. I know nothing about the internals of the API function I'm calling, so I was looking for a generic way of determining whether the function had finished. | If you call such a function, won't that reset any idle time counter, assuming one exists?
If you could outline the problem you are trying to solve it may be that we can give you a hand. I can think of ways that I would approach solving the problem of "how long has it been since this function ran" or "how long since the last event on the page" or "do something if the user has been on this page for X seconds", but I don't there is any good way of doing "do this only when nothing has happened for X seconds".
**Update**
Based on your update, I'd look for a callback mechanism in the API (could you share what it is?) that would allow you to schedule some work for after the API is complete. If that doesn't work, you could try adding something like:
```
setTimeout( function() { myCallbackMethod(); }, 0 );
```
This will schedule your callback to start once the current execution is completed. It depends on the javascript engine being single-threaded, but I've seen it used to good effect. | There are two fact you can exploit to measure the idleness of the javascript/flash thread.
1. Javascript has timing sources ([setTimeout, setInterval](http://javascript.about.com/library/blstvsi.htm)) that tick only when javascript is idle. Thus the less idle the thread, the slower the timer.
> "JavaScript can only ever execute one
> piece of code at a time (due to its
> single-threaded nature) each of these
> blocks of code are "blocking" the
> progress of other asynchronous events.
> This means that when an asynchronous
> event occurs (like a mouse click, a
> timer firing, or an XMLHttpRequest
> completing) it gets queued up to be
> executed later."
> [How JavaScript Timers Work](http://ejohn.org/blog/how-javascript-timers-work/)
2. Javascript has an external timing source which ticks regardless of idleness. The class instance [Date()](http://www.w3schools.com/jS/js_obj_date.asp) is based on an external clock, you can get millisecond timing using [getTime()](http://www.w3schools.com/jsref/jsref_getTime.asp):
var timeSinceDisco = (new Date).getTime();
eJohn has some interesting tests [using getTime() for benchmarking](http://ejohn.org/blog/accuracy-of-javascript-time/).
We use the difference between the external timer Date.getTime(), and the internal time setTimeout to calculate the degree of idleness of the javascript thread. Of course this isn't going to work as well on sexy new javascript engines like [V8](http://code.google.com/p/v8/) or [tracemonkey](https://wiki.mozilla.org/JavaScript:TraceMonkey) as they use more than one thread. It should work for most browsers currently out there.
[Lessons from Gmail: Using Timers Effectively](http://ajaxian.com/archives/lessons-from-gmail-using-timers-effectively) | How can I detect Javascript idleness? | [
"",
"javascript",
"dom",
"browser",
""
] |
Can a java programmer can create daemon threads manually? How is it? | [java.lang.Thread.setDaemon(boolean)](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean))
Note that if not set explicitly, this property is "inherited" from the Thread that creates a new Thread. | You can mark a thread as a daemon using the setDaemon method provided. According to the java doc:
> Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
>
> This method must be called before the thread is started.
>
> This method first calls the checkAccess method of this thread with no arguments. This may result in throwing a SecurityException (in the current thread).
Here an example:
```
Thread someThread = new Thread(new Runnable() {
@Override
public void run() {
runSomething();
}
});
someThread.setDaemon(true);
someThread.start();
``` | How do I create daemon threads? | [
"",
"java",
"daemon",
""
] |
```
<button type="button" value="click me" onclick="check_me();" />
function check_me() {
//event.preventDefault();
var hello = document.myForm.username.value;
var err = '';
if(hello == '' || hello == null) {
err = 'User name required';
}
if(err != '') {
alert(err);
$('username').focus();
return false;
} else {
return true; }
}
```
In Firefox, when I try to submit an empty value it throws up the error and sets the focus back to element. But same thing doesn't happen in IE as it throws up error and after clicking OK and posts the form (returns true).
How I can avoid this? I was thinking to avoid this using `event.preventDefault()`, but I am not sure how to do this using this method. I tried passing `checkme(event)` .. but it didn't work. I am using Prototype js.
(I know how to pass an event when I bind an .click function in Javascript.. instead of calling `onclick` within html .. using Jquery, but I have to debug this piece of code) | > Although this is the accepted answer, toto\_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
```
<button type="button" value="click me" onclick="return check_me();" />
``` | 1. Modify the definition of the function check\_me as::
```
function check_me(ev) {
```
2. Now you can access the methods and parameters of the event, in your case:
```
ev.preventDefault();
```
3. Then, you have to pass the parameter on the onclick in the inline call::
```
<button type="button" onclick="check_me(event);">Click Me!</button>
```
A [useful link](http://www.quirksmode.org/js/events_access.html) to understand this.
---
# Full example:
```
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
</script>
</head>
<body>
<button type="button" onclick="check_me(event);">Click Me!</button>
</body>
</html>
```
---
---
---
---
---
---
---
---
---
## Alternatives (best practices):
Although the above is the direct answer to the question (***passing an event object to an inline event***), there are other ways of handling events that [*keep the logic separated from the presentation*](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_dont_use_these)
### A. Using `addEventListener`:
```
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
<!-- add the event to the button identified #my_button -->
document.getElementById("my_button").addEventListener("click", check_me);
</script>
</body>
</html>
```
### B. Isolating Javascript:
Both of the above solutions are fine for a small project, or a hackish **quick and dirty** solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.
Just put this two files in the same folder:
* example.html:
```
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript" src="example.js"></script>
</body>
</html>
```
* example.js:
```
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);
``` | How to pass an event object to a function in Javascript? | [
"",
"javascript",
"dom-events",
""
] |
I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string
```
string = "a=0 b=1 c=3"
```
I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:
```
list = string.split()
dic = {}
for entry in list:
key, val = entry.split('=')
dic[key] = int(val)
```
But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the `val` can be a string.
```
dic = dict([entry.split('=') for entry in list])
```
However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.
```
dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])
```
So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me? | Do you mean this?
```
>>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
{'a': 0, 'c': 3, 'b': 1}
``` | How about a one-liner without list comprehension?
```
foo="a=0 b=1 c=3"
ans=eval( 'dict(%s)'%foo.replace(' ',',')) )
print ans
{'a': 0, 'c': 3, 'b': 1}
``` | convert string to dict using list comprehension | [
"",
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression",
""
] |
Our team has just started unittesting and mocking, and we have run into some discussion considering extension methods. The question is what is a good approach to testing classes, that make use of extension methods. I.e. we have an Enum like this..
```
public enum State
{
[LangID(2817)]
Draft = 0,
[LangID(2832)]
Booked = 1,
[LangID(1957)]
Overdue = 2,
[LangID(2834)]
Checked = 3,
}
```
Which makes use of the extension method:
```
public static string GetDescription(this Enum _enum)
{
Type type = _enum.GetType();
MemberInfo[] memInfo = type.GetMember(_enum.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(LangID), false);
if (attrs != null && attrs.Length > 0)
return LanguageDB.GetString(((LangID)attrs[0]).ID);
}
return _enum.ToString();
}
```
Which again will be called by the class under test, like so ..
```
public class SUT(){
public void MethodUnderTest(){
string description = SomeObject.Status.GetDescription();//Status is Type State
}
}
```
In this example the enum is getting a description in the language of the user, via LanguageDB, which unfortunately is not injected inside the class since it's static. We could naturally refractor the lot, but this would be a big investment, considering the code is working almost flawless.
Any good suggestion? | If you're using MS' test suite you can do a very simple refactoring and be able to use Accessors to inject a mock into your static type object.
Let's say you've got code like this:
```
public static void Save(this Entity data)
{
Repository.Instance.Save(data);
}
```
A static within a static... hard to test? Not really. Modify the extension class thusly:
```
private static Repository Instance
{
get
{
return _repository ?? Repository.Instance;
}
}
private static Repository _repository = null;
public static void Save(this Entity data)
{
Instance.Save(data);
}
```
Simple refactor. Now, you can use the accessor to set your mock at test time...
```
[TestInitialize(), DebuggerStepThrough]
public void Setup()
{
MyEntityExtensions_Accessor._repository = new Mock<IRepository>();
}
``` | **almost** flawless? ;-)
Rule 1: If it can't be tested don't write it.
Rule 2: Many things is life look like tehy are going to hurt, but don't.
How sure are you that this refactoring is going to be a big investment?
Rule 0: Rules are for the guidance of Wise Men and ond the obedience of Idiots.
This is a judgement call how likely are you avoid a defect in that method by the work? My guess is that in this case the benefits of refactoring that method are quite small. | Unittesting extension methods | [
"",
"c#",
"unit-testing",
"extension-methods",
""
] |
I have to create a Rails migration which creates many triggers and stored procedures.
Normally one would do that using the `execute` method, but because of the size of the statements, I'd rather keep them in an external file and reference it from the migration.
How can I do that? Is it even possible? | You can just store them in a text file and read them in via a File object.
```
sql = ""
source = File.new("./sql/procedures.sql", "r")
while (line = source.gets)
sql << line
end
source.close
execute sql
```
It's ugly, but works. I'd strongly recommend keeping the stored procedures/triggers inside migrations for easy rollbacks.
If you do the "external file" method, you'll need to maintain two additional files per migration, one for adding all the stuff, and one for dropping in in case of a:
```
rake db:rollback
``` | I did the following where we needed:
```
class RawSqlMigration < ActiveRecord::Migration
def up
execute File.read(File.expand_path('../../sql_migrations/file.sql', __FILE__))
end
end
``` | Is it possible to use an external SQL file in a Rails migration? | [
"",
"sql",
"ruby-on-rails",
"migration",
""
] |
Occassionaly I run accross this error in PHP, how can I fix this or what cause it?
> Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register\_globals is enabled. You can disable this functionality and this warning by setting session.bug\_compat\_42 or session.bug\_compat\_warn to off, respectively. in Unknown on line 0 | If your variable names are the same as the session parameters then this version of PHP will incorrectly recognize this as the programmer incorrectly relying on register\_globals for session variables. Rename your variables and the warning should go away.
```
$mySessionVar = $_session["sessionVar"];
```
and not
```
$sessionVar = $_session["sessionVar"];
``` | You are relying on a deprecated feature of PHP, called [register\_globals](http://www.php.net/manual/en/ini.core.php#ini.register-globals). This feature caused many security issues, and shouldn't be used any longer. The PHP manual discusses this [in-depth](http://www.php.net/manual/en/security.globals.php).
For an excellent description of the problem, see this [Google Groups](http://groups.google.com/group/comp.lang.php/browse_thread/thread/bac6f1c426ef4b22/c3b0666dea7d75fd?hl=en&lnk=st&q=Please+be+advised+that+the+session+extension+does+not+consider+global+variables+as+a+source+of+data#c3b0666dea7d75fd) post.
**Edit**: If you *aren't* relying on `register_globals`, then you should pay attention to Gumbo and stereointeractive's answers. | How can I avoid PHP session errors? | [
"",
"php",
"session",
""
] |
I have a new website. And the following is my scenario:
I will send an email to 5 people (numbers not important), inside the email, i will include a link for them to click:
www.domain.com/email=abc@xyz.com&key=abc...xyz
They key are randomly generated using salt and sha1 in php. Upon click the link in their email, can I directly let them access the update profile page?? Or do I need to ask them login again?
If I directly let them access the update profile page, what are the security things I need to take care? I know the use of login, can store session, but, the thing is, they click the link from their email, and I think its quite private and safe.
The only security flaw I can think of is: the hacker can magically memorize the "key" (which is about 60++ characters), and then type in browser URL: www.domain.com/email=abc@xyz.com&key=abc...xyz.
If the hackers can do that, then I am done. My users account will be hacked.
Is there anything else that hacker can hack? Just update profile page only.
**Btw, if they already update their profile, should I remove the "key" in database??**
I am using php and mysql | A password reset email should have a one-time use - store an opaque token in your database, send it in the email, and only allow it to be used once. | I agree with Paul, but for profile updating I suggest to do it after login.
You can also display and memorize the ip address of client when he resets his password. | Php, update password without login? | [
"",
"php",
"profile",
""
] |
Is there a standardized way to sync a collection of Model objects with a collection of matching ModelView objects in C# and WPF? I'm looking for some kind of class that would keep the following two collections synced up assuming I only have a few apples and I can keep them all in memory.
Another way to say it, I want to make sure if I add an Apple to the Apples collection I would like to have an AppleModelView added to the AppleModelViews collection. I could write my own by listening to each collections' CollectionChanged event. This seems like a common scenario that someone smarter than me has defined "the right way" to do it.
```
public class BasketModel
{
public ObservableCollection<Apple> Apples { get; }
}
public class BasketModelView
{
public ObservableCollection<AppleModelView> AppleModelViews { get; }
}
``` | I may not *exactly* understand your requirements however the way I have handled a similar situation is to use CollectionChanged event on the ObservableCollection and simply create/destroy the view models as required.
```
void OnApplesCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Only add/remove items if already populated.
if (!IsPopulated)
return;
Apple apple;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
apple = e.NewItems[0] as Apple;
if (apple != null)
AddViewModel(asset);
break;
case NotifyCollectionChangedAction.Remove:
apple = e.OldItems[0] as Apple;
if (apple != null)
RemoveViewModel(apple);
break;
}
}
```
There can be some performance issues when you add/remove a lot of items in a ListView.
We have solved this by: Extending the ObservableCollection to have an AddRange, RemoveRange, BinaryInsert methods and adding events that notify others the collection is being changed. Together with an extended CollectionViewSource that temporary disconnects the source when the collection is changed it works nicely.
HTH,
Dennis | I use lazily constructed, auto-updating collections:
```
public class BasketModelView
{
private readonly Lazy<ObservableCollection<AppleModelView>> _appleViews;
public BasketModelView(BasketModel basket)
{
Func<AppleModel, AppleModelView> viewModelCreator = model => new AppleModelView(model);
Func<ObservableCollection<AppleModelView>> collectionCreator =
() => new ObservableViewModelCollection<AppleModelView, AppleModel>(basket.Apples, viewModelCreator);
_appleViews = new Lazy<ObservableCollection<AppleModelView>>(collectionCreator);
}
public ObservableCollection<AppleModelView> Apples
{
get
{
return _appleViews.Value;
}
}
}
```
Using the following `ObservableViewModelCollection<TViewModel, TModel>`:
```
namespace Client.UI
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
public class ObservableViewModelCollection<TViewModel, TModel> : ObservableCollection<TViewModel>
{
private readonly ObservableCollection<TModel> _source;
private readonly Func<TModel, TViewModel> _viewModelFactory;
public ObservableViewModelCollection(ObservableCollection<TModel> source, Func<TModel, TViewModel> viewModelFactory)
: base(source.Select(model => viewModelFactory(model)))
{
Contract.Requires(source != null);
Contract.Requires(viewModelFactory != null);
this._source = source;
this._viewModelFactory = viewModelFactory;
this._source.CollectionChanged += OnSourceCollectionChanged;
}
protected virtual TViewModel CreateViewModel(TModel model)
{
return _viewModelFactory(model);
}
private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
for (int i = 0; i < e.NewItems.Count; i++)
{
this.Insert(e.NewStartingIndex + i, CreateViewModel((TModel)e.NewItems[i]));
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldItems.Count == 1)
{
this.Move(e.OldStartingIndex, e.NewStartingIndex);
}
else
{
List<TViewModel> items = this.Skip(e.OldStartingIndex).Take(e.OldItems.Count).ToList();
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
for (int i = 0; i < items.Count; i++)
this.Insert(e.NewStartingIndex + i, items[i]);
}
break;
case NotifyCollectionChangedAction.Remove:
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
// remove
for (int i = 0; i < e.OldItems.Count; i++)
this.RemoveAt(e.OldStartingIndex);
// add
goto case NotifyCollectionChangedAction.Add;
case NotifyCollectionChangedAction.Reset:
Clear();
for (int i = 0; i < e.NewItems.Count; i++)
this.Add(CreateViewModel((TModel)e.NewItems[i]));
break;
default:
break;
}
}
}
}
``` | MVVM Sync Collections | [
"",
"c#",
"wpf",
"mvvm",
""
] |
Sorry if this seems like an easy question, but I've started pulling hair out on this...
I have a XML file which looks like this...
```
<VAR VarNum="90">
<option>1</option>
</VAR>
```
I'm trying to get the **VarNum**.
So far I've been successful using the follow code to get the other information:
```
$xml=simplexml_load_file($file);
$option=$xml->option;
```
I just can't get VarNum (the attribute value I think?)
Thanks! | You should be able to get this using [SimpleXMLElement::attributes()](http://ca.php.net/manual/en/function.simplexml-element-attributes.php)
Try this:
```
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
```
That will show you all the name/value attributes for the first `foo` element. It's an associative array, so you can do this as well:
```
$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
``` | What about using `$xml['VarNum']` ?
Like this :
```
$str = <<<XML
<VAR VarNum="90">
<option>1</option>
</VAR>
XML;
$xml=simplexml_load_string($str);
$option=$xml->option;
var_dump((string)$xml['VarNum']);
```
(I've used `simplexml_load_string` because I've pasted your XML into a string, instead of creating a file ; what you are doing with `simplexml_load_file` is fine, in your case !)
Will get you
```
string '90' (length=2)
```
With simpleXML, you access attributes with an array syntax.
And you have to cast to a string to get the value, and not and instance of `SimpleXMLElement`
For instance, see **example #5** of [Basic usage](http://php.net/manual/en/simplexml.examples-basic.php) in the manual :-) | How to get the value of an attribute from XML file in PHP? | [
"",
"php",
"xml",
"simplexml",
""
] |
I'm still pretty new to c++ (coming over from java).
I have a stl list of type `Actor`. When `Actor` only contained "real" methods there was no problem. I now want to extend this class to several classes, and have a need to change some methods to be abstract, since they don't make sense as concrete anymore.
As I expected (from the documentation) this is bad news because you can no longer instantiate `Actor`, and so when I iterate through my list I run into problems.
What is the c++ way to do this?
Sorry if there's anything unclear | You can not handle this directly:
As you can see when the class is abstract you can not instanciate the object.
Even if the class where not abstract you would not be able to put derived objects into the list because of the slicing problem.
The solution is to use pointers.
So the first question is who owns the pointer (it is the responcability of the owner to delete it when its life time is over).
With a std::list<> the list took ownership by creating a copy of the object and taking ownership of the copy. But the destructor of a pointer does nothing. You need to manually call the delete on a pointer to get the destructor of the obejct to activate. So std::list<> is not a good option for holding pointers when it also needs to take ownership.
### Solution 1:
```
// Objects are owned by the scope, the list just holds apointer.
ActorD1 a1; Actor D1 derived from Actor
ActorD2 a2;
ActorD2 a3;
std::list<Actor*> actorList;
actorList.push_back(&a1);
actorList.push_back(&a2);
actorList.push_back(&a3);
```
This works fine as the list will go out of scope then the objects everything works fine. But this is not very useful for dynamically (run-time) created objects.
### Solution 2:
Boost provides a set of containers that handle pointers. You give ownership of the pointer to the container and the object is destroyed by the containter when the container goes out ofd scope.
```
boost::ptr_list<Actor> actorList;
actorList.push_back(new ActorD1);
actorList.push_back(new ActorD2);
actorList.push_back(new ActorD2);
``` | It's not possible to create a `std::list<Actor>` if the type Actor is abstract. Under the hood a list will hold an instance of the type specified in the template arguments. Because you can't ever have an instance of an abstract class this won't ever work.
What you can do though is use a level of indirection like a pointer. It is legal to have an instance of a pointer to an abstract class and hence legal to make a `stl::list<Actor*>`. | Using abstract class as a template type | [
"",
"c++",
"inheritance",
"abstract-class",
""
] |
I have a simple problem that reads an Excel file (using interop) and fills an MSSQL database file with some data extracted from it. That's fine so far.
I have a Shops table with the following fields:
* ID: int, auto-generated, auto-sync: on insert
* Name: string
* Settlement: string
* County: string
* Address: string
I read the excel file, and then create a new Shops object and set the Name, Settlement, County and Address properties and I call Shops.InsertOnSubmit() with the new Shops object.
After this I have to reset the database (at least, the table), for which the easiest way I found was to call the DeleteDatabase() method and then call CreateDatabase() again.
The problem is, that after the first reset, when I try to fill the table again, I get the exception: The database generated a key that is already in use.
Additionally, from that point on, I'm unable to use that database file, because DatabaseExists() returns FALSE, but when I call the CreateDatabase() method, it throws an exception, that the database already exists (although the data files don't exist).
What am I doing wrong?
Thank you very much in advance! | It sounds like you are re-using the data-context beyond what is wise. Try disposing and re-creating the data-context after deleting the database.
I suspect the problem is that the identity manager is still tracking objects (destroying and recreating the database is such an edge-case that I think we can forgive it for not resetting itself here). | I encountered this error. I had a log table, with an identity. I was truncating the log, while my application was running. What happened was the DB would start the identity column over again when I truncated, however the data context I was using to log still had objects it was tracking with the same key. | LINQ to SQL - The database generated a key that is already in use | [
"",
"c#",
"sql-server",
"linq-to-sql",
""
] |
I need to add some non printable chars to a string in java so it can be sent down a tcp pipe. the chars mean something to the protocol I am using (record separator and end of message respectively)
what is the best way to go about doing this?
Ideally I'l like to refer to them as constants so that I can use string concatonation/stringbuilder/string.format to add them where required, without having to type them out.
For the curious the chars I need are ASCIIx1E (Record separator) and ACSIIx03 (End of Text). | ```
public final class ProtocolConstants {
public final char RECORD_SEPARATOR = 0x1e;
public final char END_OF_TEXT = 0x03;
private ProtocolConstants() {}
}
```
something like that? | If you wish, you can write these as Unicode literals (in chars or Strings):
```
final String endOfText = "\u0003";
```
* [Unicode charts](http://unicode.org/charts/)
* [Java Language Specification Lexical Structure chapter](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html)
I am assuming that you don't literally want [ASCII](http://en.wikipedia.org/wiki/ASCII) for a byte-based protocol (the chars are still 16 bits). | Adding non printable chars to a string in Java? | [
"",
"java",
"string",
"ascii",
""
] |
I am creating menu for a website. for each item (Home, Contact us, About us) I use Background color and text of size 125X30. In CSS, When i use float it works correct. But when i removed float, all individual item such as home, contact etc come down one by one. I need it left to right in a single line without float. Help me | Rajasekar,
Stu Nicholls of CSSplay has the following horizontal menu without using floats:
**CSS**
```
.menu {display:inline-block;}
.menu {display:inline;}
.holder {display:table;}
.menu {
display:table-row;
padding:0;
margin:0;
list-style-type:none;
white-space:nowrap;
}
.menu li {display:inline;}
.menu a, .menu a:visited {
display:block;
float:left;
padding:4px 16px;
color:#000;
background:#d4d4d4;
border:1px solid #fff;
text-decoration:none;
}
.menu a:hover {
color:#fff;
background:#08c;
}
#wrapper1 {text-align:left;}
#wrapper1 .holder {margin:0;
```
**html**
```
<div id="wrapper1">
<div class="holder">
<ul class="menu">
<li><a href="#nogo">Tab One</a></li>
<li><a href="#nogo">Tab Two: Longer</a></li>
<li><a href="#nogo">Tab Three: Longest</a></li>
<li><a href="#nogo">Tab Four</a></li>
</ul>
</div>
</div>
```
Further explanation (including the use of display:inline-block) [is on CSSplay](http://www.cssplay.co.uk/menus/centered2.html). | If float is working, I'd recommend sticking with that - you might just need a clearing element afterwards, since this is a common source of problems.
If you really can't go with floats, you could use `display: inline-block` | How to Prevent Linke break for Divs in CSS? | [
"",
"php",
"html",
"css",
"layout",
""
] |
I'm trying to match the following using a regular expression in Java - I have some data separated by the two characters 'ZZ'. Each record starts with 'ZZ' and finishes with 'ZZ' - I want to match a record with no ending 'ZZ' for example, I want to match the trailing 'ZZanychars' below (Note: the \*'s are not included in the string - they're just marking the bit I want to match).
ZZanycharsZZZZanycharsZZ**ZZanychars**
But I don't want the following to match because the record has ended:
ZZanycharsZZZZanycharsZZZZanycharsZZ
EDIT: To clarify things - here are the 2 testcases I am using:
```
// This should match and in one of the groups should be 'ZZthree'
String testString1 = "ZZoneZZZZtwoZZZZthree";
// This should not match
String testString2 = "ZZoneZZZZtwoZZZZthreeZZ";
```
EDIT: Adding a third test:
```
// This should match and in one of the groups should be 'threeZee'
String testString3 = "ZZoneZZZZtwoZZZZthreeZee";
``` | To match only the final, unterminated record:
```
(?<=[^Z]ZZ|^)ZZ(?:(?!ZZ).)++$
```
The starting delimiter is two `Z`'s, but there can be a third `Z` that's considered part of the data. The lookbehind ensures that you don't match a `Z` that's part of the previous record's ending delimiter (since an ending delimiter can *not* be preceded by a non-delimiter `Z`). However, this assumes there will never be empty records (or records containing only a single `Z`), which could lead to eight or more `Z`'s in a row:
```
ZZabcZZZZdefZZZZZZZZxyz
```
If that were possible, I would forget about trying to match the final record by itself, and instead match *all* of them from the beginning:
```
(?:ZZ(?:(?!ZZ).)*+ZZ)*+(ZZ(?:(?!ZZ).)++$)
```
The final, unterminated record is now captured in group #1. | (Edited after the post of the 3rd example)
Try:
```
(?!ZZZ)ZZ((?!ZZ).)++$
```
Demo:
```
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String[] tests = {
"ZZoneZZZZtwoZZZZthree",
"ZZoneZZZZtwoZZZZthreeZZ",
"ZZoneZZZZtwoZZZZthreeZee"
};
Pattern p = Pattern.compile("(?!ZZZ)ZZ((?!ZZ).)++$");
for(String tst : tests) {
Matcher m = p.matcher(tst);
System.out.println(tst+" -> "+(m.find() ? m.group() : "no!"));
}
}
}
``` | What Java regular expression do I need to match this text? | [
"",
"java",
"regex",
"parsing",
""
] |
I have two jps pages to handle an upload of the single file.
Here is a code for selecting a file:
```
org.apache.commons.io.FilenameUtils, java.util.*,
java.io.File, java.lang.Exception" %>
...
<form name="uploadFile" method="POST" action="processUpload.jsp"
enctype="multipart/form-data">
<input type="file" name="myfile"><br />
<input type="submit" value="Submit" />
</form>
....
```
//--------handle uploaded file---------------------
```
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
<%
System.out.println("Content Type ="+request.getContentType());
System.out.println("Cookies" + request.getCookies());
DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(1000000);
List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();
while(itr.hasNext()) {
FileItem fi = (FileItem)itr.next();
//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if(!fi.isFormField()) {
System.out.println("\nNAME: "+fi.getName());
System.out.println("SIZE: "+fi.getSize());
//System.out.println(fi.getOutputStream().toString());
File fNew= new File(application.getRealPath("/"), fi.getName());
System.out.println(fNew.getAbsolutePath());
fi.write(fNew);
}
else {
System.out.println("Field ="+fi.getFieldName());
}
}
%>
```
This code put a file into my build\web folder.
How to set a path to a different directory on the server (assuming the write permissions are set) ?
Thanks, | Use the following code (adapted for the [user guide](http://commons.apache.org/fileupload/using.html)):
```
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(dir);
// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
``` | Why simply not specify the path when creating the file? You could set the path as part of your application configuration (JNI), or as a system property when the web server starts (using the -Dpath=...), and reading it using System.getProperty("path"). You could even use an environment variable defined on your system and read that environment variable using the [System.getenv](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getenv(java.lang.String)) method.
Alternativaly, you could create just a temporary file using the File.getTempFile method. If you just need to save the file to do something with it and never use it again, that's a better option - nevertheless, you have to delete the file yourself after you use it. | upload file in JSP - how to change a default path for the uploaded file | [
"",
"java",
"jsp",
"upload",
""
] |
I am trying to write a proxy which reads an image from one server and returns it to the HttpContext supplied, but I am just getting character stream back.
I am trying the following:
```
WebRequest req = WebRequest.Create(image);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter (context.Response.OutputStream);
sw.Write (sr.ReadToEnd());
```
But as I mentioned earlier, this is just responding with text.
How do I tell it that it is an image?
Edit: I am accessing this from within a web page in the source attribute of an img tag. Setting the content type to application/octet-stream prompts to save the file and setting it to image/jpeg just responds with the filename. What I want is the image to be returned and displayed by the calling page. | Since you are working with binary, you don't want to use `StreamReader`, which is a **Text**Reader!
Now, assuming that you've set the content-type correctly, you should just use the response stream:
```
const int BUFFER_SIZE = 1024 * 1024;
var req = WebRequest.Create(imageUrl);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
var bytes = new byte[BUFFER_SIZE];
while (true)
{
var n = stream.Read(bytes, 0, BUFFER_SIZE);
if (n == 0)
{
break;
}
context.Response.OutputStream.Write(bytes, 0, n);
}
}
}
``` | You're going to need to set the Content Type on your response. Here's a snippet of code that'll do it:
```
// specify that the response is a JPEG
// Also could use "image/GIF" or "image/PNG" depending on what you're
// getting from the server
Response.ContentType = "image/JPEG";
``` | Reading Image from Web Server in C# proxy | [
"",
"c#",
"http",
"image",
"stream",
""
] |
I'm running a Powershell test script from a C# application. The script can fail due to a bad cmdlet which causes pipe.Invoke() to throw an exception.
I'm able to capture all the information I need about the exception, but I'd like to be able to display the script's output up to that point. I haven't had any luck since results appears to be null when an exception is thrown.
Is there something I'm missing? Thanks!
```
m_Runspace = RunspaceFactory.CreateRunspace();
m_Runspace.Open();
Pipeline pipe = m_Runspace.CreatePipeline();
pipe.Commands.AddScript(File.ReadAllText(ScriptFile));
pipe.Commands.Add("Out-String");
try {
results = pipe.Invoke();
}
catch (System.Exception)
{
m_Runspace.Close();
// How can I get to the Powershell output that comes before the exception?
}
``` | The solution I ended up using was to implement our own PSHost to handle PowerShell's output. The initial information for this came from <http://community.bartdesmet.net/blogs/bart/archive/2008/07/06/windows-powershell-through-ironruby-writing-a-custom-pshost.aspx> in the "Building a custom PS host" section.
In my case it did require using a custom PSHostRawUserInterface as well.
Here's the quick overview of what was done. I've only listed the function I actually implimented, but there's many that are just contain throw new NotImplementedException();
```
private class myPSHost : PSHost
{
(Same as what the above link mentions)
}
private class myPSHostUI : PSHostUserInterface
{
private myPSHostRawUI rawui = new myPSHostRawUI();
public override void Write // all variations
public override PSHostRawUserInterface RawUI { get { return rawui; } }
}
private class myPSHostRawUI : PSHostRawUserInterface
{
public override ConsoleColor ForegroundColor
public override ConsoleColor BackgroundColor
public override Size BufferSize
}
``` | Not sure if this is helpful. I am guessing you are running V1. This V2 approach doesn't throw and prints the result:
```
Hello World
67 errors
string script = @"
'Hello World'
ps | % {
$_.name | out-string1
}
";
PowerShell powerShell = PowerShell.Create();
powerShell.AddScript(script);
var results = powerShell.Invoke();
foreach (var item in results)
{
Console.WriteLine(item);
}
if (powerShell.Streams.Error.Count > 0)
{
Console.WriteLine("{0} errors", powerShell.Streams.Error.Count);
}
``` | Capturing Powershell output in C# after Pipeline.Invoke throws | [
"",
"c#",
"powershell",
"powershell-1.0",
""
] |
I have a problem with ObservableCollection Class. I cant resolve this.
```
using System.Collections.ObjectModel;
#region ViewModelProperty: CustomerList
private ObservableCollection<T> _customerList = new ObservableCollection<T>();
public ObservableCollection<T> CustomerList
{
get
{
return _customerList;
}
set
{
_customerList = value;
OnPropertyChanged("CustomerList");
}
}
#endregion
```
My class with the ObservableCollection inherits ViewModelBase:
```
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
```
any idea, where is the problem? | `T` is just a placeholder. You need to supply an actual type somewhere for `T`.
E.g. if you have `List<T>`, you could make a `List<int>` or `List<string>` (`T` is any other type which fits the given constraints). I.e. `T` is `int` in the first case and `string` in the second. | I think that it will become clear to you when you read up a bit on [Generics](http://msdn.microsoft.com/en-us/library/ms172192.aspx)
You could do it like this:
```
ObservableCollection<Customer> customerList = new ObservableCollection<Customer>()
```
Then, you have a typed collection which will be able to store instances of the Customer class (and also instances of subclasses that inherit from Customer).
So, if you want to have a collection where you want to be able to add instances of multiple types, you could create a base-class (or interface), and inherit from that base-class or implement this interface, and create an ObservableCollection instance for ex. | Cannot resolve symbol T | [
"",
"c#",
"wpf",
"observablecollection",
""
] |
With Java `Iterator`s, I have used the `hasNext` method to determine whether an iteration has more elements (without consuming an element) -- thus, `hasNext` is like a "`Peek`" method.
My question: is there anything like a "`hasNext`" or "`Peek`" method with C#'s generic `IEnumerator`s? | No, unfortunately there isn't.
The [`IEnumerator<T>`](http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx) interface only exposes the following members:
**Methods:**
> `Dispose`
> `MoveNext`
> `Reset`
**Properties**:
> `Current` | No, but in C# you can repeatedly ask for the current element without moving to the next one. It's just a different way of looking at it.
It wouldn't be *too* hard to write a C# class to take a .NET-style `IEnumerator` and return a Java-style `Iterator`. Personally I find the .NET style easier to use in most cases, but there we go :)
EDIT: Okay, this is completely untested, but I *think* it will work. It does at least compile :)
```
using System;
using System.Collections;
using System.Collections.Generic;
// // Mimics Java's Iterable<T> interface
public interface IIterable<T>
{
IIterator<T> Iterator();
}
// Mimics Java's Iterator interface - but
// implements IDisposable for the sake of
// parity with IEnumerator.
public interface IIterator<T> : IDisposable
{
bool HasNext { get; }
T Next();
void Remove();
}
public sealed class EnumerableAdapter<T> : IIterable<T>
{
private readonly IEnumerable<T> enumerable;
public EnumerableAdapter(IEnumerable<T> enumerable)
{
this.enumerable = enumerable;
}
public IIterator<T> Iterator()
{
return new EnumeratorAdapter<T>(enumerable.GetEnumerator());
}
}
public sealed class EnumeratorAdapter<T> : IIterator<T>
{
private readonly IEnumerator<T> enumerator;
private bool fetchedNext = false;
private bool nextAvailable = false;
private T next;
public EnumeratorAdapter(IEnumerator<T> enumerator)
{
this.enumerator = enumerator;
}
public bool HasNext
{
get
{
CheckNext();
return nextAvailable;
}
}
public T Next()
{
CheckNext();
if (!nextAvailable)
{
throw new InvalidOperationException();
}
fetchedNext = false; // We've consumed this now
return next;
}
void CheckNext()
{
if (!fetchedNext)
{
nextAvailable = enumerator.MoveNext();
if (nextAvailable)
{
next = enumerator.Current;
}
fetchedNext = true;
}
}
public void Remove()
{
throw new NotSupportedException();
}
public void Dispose()
{
enumerator.Dispose();
}
}
public sealed class IterableAdapter<T> : IEnumerable<T>
{
private readonly IIterable<T> iterable;
public IterableAdapter(IIterable<T> iterable)
{
this.iterable = iterable;
}
public IEnumerator<T> GetEnumerator()
{
return new IteratorAdapter<T>(iterable.Iterator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public sealed class IteratorAdapter<T> : IEnumerator<T>
{
private readonly IIterator<T> iterator;
private bool gotCurrent = false;
private T current;
public IteratorAdapter(IIterator<T> iterator)
{
this.iterator = iterator;
}
public T Current
{
get
{
if (!gotCurrent)
{
throw new InvalidOperationException();
}
return current;
}
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
gotCurrent = iterator.HasNext;
if (gotCurrent)
{
current = iterator.Next();
}
return gotCurrent;
}
public void Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
iterator.Dispose();
}
}
``` | Is there a "HasNext" method for an IEnumerator? | [
"",
"c#",
"iterator",
"ienumerator",
"peek",
""
] |
Is there any optimization library in C#?
I have to optimize a complicated equation in excel, for this equation there are a few coefficients. And I have to optimize them according to a fitness function that I define. So I wonder whether there is such a library that does what I need? | Here are a few free and open source c# implementrions
* [Nelder Mead Simplex implementation](http://lflemmer.wordpress.com/2007/04/07/a-c-implementation-of-the-nelder-mead-simplex-algorithm/) [[Alternate Link](https://code.google.com/archive/p/nelder-mead-simplex/)]
* [Numerical](http://numerical.codeplex.com/) provides a variety of algorithms including:
+ Chromosome Manager
+ Genetic Optimizer
+ Hill Climbing Optimizer
+ Maximizing Point
+ Maximizing PointFactoy
+ Maximizing Vector
+ Minimizing Point
+ Minimizing Point Factory
+ Minimizing Vector
+ Multi Variable General Optimizer
+ Multi Variable Optimizer
+ One Variable Function Optimizer
+ Optimizing Bracket Finder
+ Optimizing Point
+ Optimizing Point Factory
+ Optimizing Vector
+ Simplex Optimizer
+ Vector Chromosome Manager
+ Vector Genetic Optimizer
+ Vector Projected Function
* [DNAnalytics](http://dnanalytics.codeplex.com/)
+ Done as both a pure managed solution and as a thin wrapper over the Intel unmanaged code.
+ is being merged into [MathNetNumerics](http://mathnetnumerics.codeplex.com/)
More can be found at this [list](http://en.wikipedia.org/wiki/List_of_numerical_libraries)
Note that optimizers frequently benefit from the more extreme code (or assembly) optimizations that are not really possible in pure managed c#. IF serious speed is a concern then targeting an unmanaged implementation like NAG or MOSEK may well provide significant benefits that outweigh the hassle of making the data accessible to the unmanaged API (pinning the managed buffer or using memory mapped files for example) | One option is [Microsoft Solver Foundation](http://msdn.microsoft.com/en-us/devlabs/hh145003.aspx), also has an [express edition](http://code.msdn.microsoft.com/solverfoundation/Release/ProjectReleases.aspx?ReleaseId=1799) | Free optimization library in C# | [
"",
"c#",
"mathematical-optimization",
""
] |
How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server. | I haven't tried it, but this [pysftp](http://pypi.python.org/pypi/pysftp/) module might help, which in turn uses paramiko. I believe everything is client-side.
The interesting command is probably `.execute()` which executes an arbitrary command on the remote machine. (The module also features `.get()` and `.put` methods which allude more to its FTP character).
UPDATE:
I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird. | You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:
> Fabric is a Python library and
> command-line tool designed to
> streamline deploying applications or
> performing system administration tasks
> via the SSH protocol. It provides
> tools for running arbitrary shell
> commands (either as a normal login
> user, or via sudo), uploading and
> downloading files, and so forth.
I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client.
The app used to be [here](http://www.nongnu.org/fab/). It can now be found [here](http://docs.fabfile.org/0.9/).
```
* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric
```
There are several good articles on it, though you should be careful because it has changed in the last six months:
[Deploying Django with Fabric](http://lethain.com/entry/2008/nov/04/deploying-django-with-fabric/)
[Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip](http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/)
[Simple & Easy Deployment with Fabric and Virtualenv](http://lincolnloop.com/blog/2008/dec/07/simple-easy-deployment-fabric-and-virtualenv/)
---
Later: Fabric no longer requires paramiko to install:
```
$ pip install fabric
Downloading/unpacking fabric
Downloading Fabric-1.4.2.tar.gz (182Kb): 182Kb downloaded
Running setup.py egg_info for package fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Downloading/unpacking ssh>=1.7.14 (from fabric)
Downloading ssh-1.7.14.tar.gz (794Kb): 794Kb downloaded
Running setup.py egg_info for package ssh
Downloading/unpacking pycrypto>=2.1,!=2.4 (from ssh>=1.7.14->fabric)
Downloading pycrypto-2.6.tar.gz (443Kb): 443Kb downloaded
Running setup.py egg_info for package pycrypto
Installing collected packages: fabric, ssh, pycrypto
Running setup.py install for fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Installing fab script to /home/hbrown/.virtualenvs/fabric-test/bin
Running setup.py install for ssh
Running setup.py install for pycrypto
...
Successfully installed fabric ssh pycrypto
Cleaning up...
```
This is mostly cosmetic, however: ssh is a fork of paramiko, the maintainer for both libraries is the same (Jeff Forcier, also the author of Fabric), and [the maintainer has plans to reunite paramiko and ssh under the name paramiko](http://bitprophet.org/blog/2012/09/29/paramiko-and-ssh/). (This correction via [pbanka](https://stackoverflow.com/users/687980/pbanka).) | What is the simplest way to SSH using Python? | [
"",
"python",
"linux",
"unix",
"ssh",
""
] |
I've used the Matrix class a thousand times. I have an elementary grasp of matrix mathematics, it's been years since I've had a class on the subject. But I don't fully understand what this class is doing under the hood to manipulate the points in a GraphicsPath.
What, specifically, is it doing in there as it pertains to GraphicsPaths in particular? Or another way to look at it, if the Matrix class didn't exist, and I had to create my own, what would it look like and what would it do? (I'm not creating my own I just want to understand it)
Furthermore, does anyone know the dimensions of the matrix used in the Matrix class?
EDIT: I've narrowed it down to the following call in reflector. From there, I've got bub kiss.
```
[DllImport("gdiplus.dll", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
internal static extern int GdipTransformPath(HandleRef path, HandleRef matrix);
``` | In this case, the Matrix class is a 2D transformation matrix. The Matrix is used to scale, rotate and / or translate the graphics path. The math is relatively straight forward. You can look at it here:
<http://en.wikipedia.org/wiki/Transformation_matrix> | One important thing to note if you are creating your own matrix class that is converting back and forth to the System.Drawing.Matrix class, is that the .NET one does not use the most commonly used standard when transforming points.
The .NET Matrix seems to be transposed before the transformation is taking place.
Also read the background here: <http://www.codeproject.com/KB/recipes/psdotnetmatrix.aspx> | System.Drawing.Matrix, I understand what it does, but how does it work? | [
"",
"c#",
".net",
"gdi+",
"matrix",
"system.drawing",
""
] |
I'm new to JQuery, but wish to use it in a site that I'm building.
When the user mouses over an item in the menu with *li* class `hovertriggerssubhead`, I want to display some text below it, located in the div (nested inside the li) with id `NavSubhead`. I have looked at several examples of this, namely in the cookbook in the FAQ of the JQuery documentation and the code of the JQuery site itself.
This is my HTML code:
```
<div id="Navigation">
<ul>
<li class="current">
<a href="index.html">Home</a></li>
<li class="hovertriggerssubhead">
<a href="gallery.html">Gallery</a>
<div class="NavSubhead">
<p class="navsubheadtext">Under Construction</p>
</div>
</li>
<li class="hovertriggerssubhead">
<div class="NavSubhead">
<p class="navsubheadtext">Under Construction</p>
</div>
<a href="contact.html">Contact</a></li>
</ul>
</div>
```
I tried two methods of accomplishing this in my JQuery code; they are below:
```
$(document).ready(function() {
//first method
$(".NavSubhead").hide();
$('#Navigation li').hover(
function(){$(this).find('div.NavSubhead:hidden').fadeIn(500);},
function(){$(this).find('div.NavSubhead:visible').fadeOut(500);}
);
//second method
$("#Navigation li div").hide();
$("#Navigation li.hovertriggerssubhead").hover(
function () {
$(this).children("div.NavSubhead").show();
},function(){
$(this).children("div.NavSubhead").hide();
});//hover
});// document ready
```
Any help would be appreciated. Thanks!
**UPDATE**: I've tried numerous answers, even one with a working demo, but it still doesn't work, which is very weird. Could it be related by any chance to constraints of the navigation html because of an encompassing table? The table has a fixed width. Other than that, I don't know what is the problem, and JQuery is referenced correctly. Thanks in advance!
**UPDATE #2**: As it's possible that this is not working because of some weird constraints in regards to my HTML, I'm going to post it here. As you can see below, I'm using [this](http://code.google.com/p/slideshow/) Slideshow framework too.
```
<html>
<head>
<title>MZ Photography</title>
<!-- Jquery Stuff -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
/*
$(function() {
$("div.NavSubhead").hide();
$('#Navigation li a').hover(
function(){$(this).next().stop(false, true).slideDown().fadeIn(500);},
function(){$(this).next().stop(false, true).slideUp().fadeOut(500);}
);
});
*/
$(function() {
/* hacky nav highlighting */
var loc = window.location.href;
//strip the existing current state
$('#Navigation .current').removeClass('current');
//add class to current section...
//Home
if(loc.indexOf('MZPhotography.html') > -1){
$('#Navigation #home').addClass('current');
}
//Gallery
else if(loc.indexOf('gallery') > -1){
$('#Navigation #gallery').addClass('current');
}
//Contact
else if(loc.indexOf('contact.html') > -1){
$('#Navigation #contact').addClass('current');
}
});
$(document).ready(function() {
$("div.NavSubhead").hide();
$('#Navigation li a').hover(
function(){$(this).next().stop(false, true).slideDown().fadeIn(500);},
function(){$(this).next().stop(false, true).slideUp().fadeOut(500);}
);
});
</script>
<!-- End jquery stuff -->
<!-- Slideshow stuff begins here -->
<link rel="stylesheet" type="text/css" href="css/slideshow.css" media="screen" />
<script type="text/javascript" src="js/mootools.js"></script>
<script type="text/javascript" src="js/slideshow.js"></script>
<script type="text/javascript">
//<![CDATA[
window.addEvent('domready', function(){
var data = {
'30.jpg': { caption: '' },
'25.jpg': { caption: '' },
'21.jpg': { caption: '' },
'16.jpg': { caption: '' },
'11.jpg': { caption: '' },
'13.jpg': { caption: '' },
'12.jpg': { caption: '' },
'9.jpg': { caption: '' },
'4.jpg': { caption: '' },
'2.jpg': { caption: '' },
'3.jpg': { caption: '' },
'6.jpg': { caption: '' },
'7.jpg': { caption: '' },
'14.jpg': { caption: '' },
'8.jpg': { caption: '' },
'10.jpg': { caption: '' },
'15.jpg': { caption: '' },
'17.jpg': { caption: '' },
'22.jpg': { caption: '' },
'28.jpg': { caption: '' },
'26.jpg': { caption: '' },
'27.jpg': { caption: '' },
'24.jpg': { caption: '' },
'23.jpg': { caption: '' },
'19.jpg': { caption: '' },
'18.jpg': { caption: '' },
'20.jpg': { caption: '' },
'29.jpg': { caption: '' },
'31.jpg': { caption: '' },
'32.jpg': { caption: '' },
'1.jpg': { caption: '' },
'5.jpg': { caption: '' },
'33.jpg': { caption: '' },
'34.jpg': { caption: '' },
'35.jpg': { caption: '' },
'36.jpg': { caption: '' }
};
var myShow = new Slideshow('show', data, {controller: true, height: 450, hu: 'images/', thumbnails: false, width: 600});
});
//]]>
</script>
<!-- end Slideshow -->
<link rel="stylesheet" href="site.css">
</head>
<body>
<table width="980"> <!--980 -->
<tr>
<td width="880">
<table width="880"> <!--880-->
<tr>
<td align="left">
<div id="logo">
<img src="images/title.png" />
</div>
</td>
<td align="right"><!--MENU-->
<div id="Navigation">
<ul>
<li id="home" class="current">
<a href="#top">Home</a></li>
<li id="gallery" class="hovertriggerssubhead">
<a href="gallery.html">Gallery</a>
<div class="NavSubhead">
<p class="navsubheadtext">Under Construction</p>
</div>
</li>
<li id="contact" class="hovertriggerssubhead">
<a href="contact.html">Contact</a></li>
<div class="NavSubhead">
<p class="navsubheadtext">Under Construction</p>
</div>
</ul>
</div>
</td>
</tr>
</table>
<table width="700">
<tr><td><br></td></tr>
<tr>
<!-- we don't rly need this -->
<!-- How about about section here? -->
<td align="left" id="tdAbout">
<!--Recent Changes --> <!-- NM -->
<div id="aboutDiv">
<p class="yellowboxtransparent" id="about">
Welcome to MZ's personal photography site. Here, you will find galleries of some of his photos, by pressing the Galleries link at the top right hand side of the page. Enjoy!
</p>
</div>
<!-- About --> </td>
<td> </td>
<td align="center">
<!--Slideshow-->
<div align="center" id="show" class="slideshow">
<img src="images/1.jpg" alt="" />
</div>
</td>
<td align="right">
</td>
</tr>
<tr><td><br><br></td></tr>
<tr><!--<td align="left"> -->
<!--Copyright Statement-->
<!--<p class="copy">© Copyright 2009 by MZ. <br/>All Rights Reserved. </p>
</td><td align="right"><!--Links--><!--</td>--></tr></table>
</td>
<td><!--Right hand column -->
<div id="meDiv">
<p class="blueboxtransparent">
hi
</p>
</div>
</td>
</tr>
</table>
<br/><br/><br/><br/><br/>
<!-- Beneath -->
<div id="bottom">
<div class="leftfloat" id="divCopy">
<!--Copyright Statement-->
<p class="copy">© Copyright 2009 by MZ. All Rights Reserved. </p>
</div>
<div class="rightfloat" id="divLinks">
<ul id="linklist">
<li><a href="http://absolutely2nothing.wordpress.com">Blog</a></li>
<li><a href="http://twitter.com/maximz2005">Twitter - @maximz2005</a></li>
</ul>
</div>
</div>
</body>
</html>
```
The below is my css, in *site.css*.
```
/* CSS for MZ Photography site. Coypright 2009 by MZ, All Rights Reserved. */
p.copy { color:#ffffff; font-face:Helvetica,Calibri,Arial; font-size:12; font-style:italic;}
.leftfloat { float: left; }
.rightfloat { float: right; }
body {
font: 12px/1.5 Helvetica, Arial, "Lucida Grande", "Lucida Sans Unicode", Tahoma, sans-serif!important;
color: #ffffff;
background: #000000; }
#about { color: #3399FF; } /* #666 */
h1 { font: Helvetica, "Comic Sans MS", "Arial Rounded MT Bold", Tahoma, "Times New Roman"; font-size: 32pt; color: #339; }
h2 { font: Helvetica, Arial; font-size: 18pt; color: #666; }
a.hover { background-color:#666; color:#ffffff; }
#tdAbout { width:25 }
#nav { float:right }
#linklist
{
font-family: Calibri, Helvetica, Comic Sans MS, Arial, sans-serif;
list-style-type:circle;
white-space:nowrap;
}
#linklist li
{
display:inline
}
/* Warnings/Alerts */
.warning, .alert, .yellowbox {
padding: 6px 9px;
background: #fffbbc;
border: 1px solid #E6DB55;
}
.yellowboxtransparent, .warningtransparent, .alerttransparent {
padding:6px 9px;
border: 1px solid #E6DB55;
}
/* Errors */
.error, .redbox {
padding: 6px 9px;
background: #ffebe8;
border: 1px solid #C00;
}
.redboxtransparent, .errortransparent{
padding: 6px 9px;
border: 1px solid #C00;
}
/* Downloads */
.download, .greenbox {
padding: 6px 9px;
background: #e7f7d3;
border: 1px solid #6c3;
}
.greenboxtransparent, .downloadtransparent {
padding: 6px 9px;
border: 1px solid #6c3;
}
/*Info Box */
.bluebox, .info{
padding: 6px 9px;
background: #FFFF33;
border: 2px solid #3399FF;
color: 000000;
}
.blueboxtransparent, .infotransparent{
padding: 6px 9px;
border: 1px solid #3399FF;
}
a:link {
COLOR: #DC143C; /* #0000FF */
}
a:visited {
COLOR: #DC143C; /* #800080 */
}
a:hover { color: #ffffff; background-color: #00BFFF; }
}
a:active { color: #ffffff; background-color: #00BFFF; }
/*Navigation*/
#Navigation {
float: right;
background: #192839 url(images/bg_nav_left.gif) left bottom no-repeat;
}
#Navigation ul {
float: left;
background: url(images/bg_nav_right.gif) right bottom no-repeat;
padding: 0 .8em 2px;
margin: 0;
}
#Navigation li {
float: left;
list-style: none;
margin: 0;
background: none;
padding: 0;
}
#Navigation li a {
float: left;
padding: 0 1em;
line-height: 25px;
font-size: 1.2em;
color: #D0D0D0;
text-decoration: none;
margin-bottom: 2px;
}
#Navigation li.current a, #Navigation li.current a:hover {
border-bottom: 2px solid #176092;
background: #192839;
margin-bottom: 0;
cursor: default;
color: #D0D0D0;
}
#Navigation li a:hover {
color: #fff;
border-bottom: 2px solid #4082ae;
margin-bottom: 0;
}
#Navigation li.current a, #Navigation li.current a:hover {
border-bottom: 2px solid #176092;
background: #192839;
margin-bottom: 0;
cursor: default;
color: #D0D0D0;
}
```
Thanks so much in advance for all your help! | **[Working Demo](http://jsbin.com/omezu)**
jQuery code
```
$(function() {
$("div.NavSubhead").hide();
$('#Navigation li a').hover(
function(){$(this).next().stop(false, true).fadeIn(500);},
function(){$(this).next().stop(false, true).fadeOut(500);}
);
});
```
*N.B. I have added a click event handler to prevent the default action on anchor elements in the demo too*
You may also want to chain in a `slideDown()` and `slideUp()` before the `fade` command in each event handler, respectively, to make the animation smoother
```
$('#Navigation li a').hover(
function(){$(this).next().stop(false, true).slideDown().fadeIn(500);},
function(){$(this).next().stop(false, true).slideUp().fadeOut(500);}
);
```
You may also want to take a look at the [jQuery accordion](http://docs.jquery.com/UI/Accordion), which essentially does what you are doing here, but has some additional options too.
**EDIT:**
After both of your updates, I know what the problem is. The slideshow plugin that you are using is for the Mootools JavaScript framework. The code supplied here is for the jQuery JavaScript framework. Whilst it is fine to use both frameworks on your site on the same page, both frameworks assign an object to `$` to use for selection, and the object in each case has different methods, properties, etc. So, to get both frameworks to work at the same time we need to avoid this conflict. Luckily, jQuery has a command to easily get around this, [`noConflict()`](http://docs.jquery.com/Core/jQuery.noConflict), which will release the `$` shorthand so that other frameworks can use it. Take particular note of the order in which it must be included in a page.
So to get the code working, the structure of the scripts will need to be as follows
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
// you can assign the jQuery object to another name if you want. Just
// use var $j = jQuery.noConflict() and then can use $j() for jQuery object.
jQuery.noConflict();
// now your jQuery stuff comes here
// there are a couple of techniques that can be used so that you can use the $
// shorthand with jQuery library. I'll show you one here using a self-invoking
// anonymous function that takes one parameter, $, into which we will pass the
// the jQuery object
(function($) {
$(function() {
$("div.NavSubhead").hide();
$('#Navigation li a').hover(
function(){$(this).next().stop(false, true).fadeIn(500);},
function(){$(this).next().stop(false, true).fadeOut(500);}
);
});
})(jQuery);
// now put the Mootools script and relevant slideshow script.
<script src="....." ></script>
....
```
There are [plenty of great slideshow and lightbox plugins for jQuery](http://speckyboy.com/2009/06/03/15-amazing-jquery-image-galleryslideshow-plugins-and-tutorials/) that offer similar effects to the Mootools one that you have linked to.
I'm of the opinion that, unless *absolutely* necessary for some specific functional need, I stick to using just one JavaScript framework in my site. Not only does this avoid conflicts, but there are usually ways built into a framework of achieving what another framework does. Even if a framework does not have that functionality as part of the core library, frameworks are designed to be extensible and as such, have an architecture that allows one to develop plugins and extend functionality to fit ones needs. | This worked for me. You should probably be consistent in your markup though and have the hidden text appear after its associated link in both cases.
```
$(document).ready(function()
{
$('.NavSubhead').hide();
$('li.hovertriggerssubhead').hover(
function()
{
$('.NavSubhead', $(this)).show();
},
function()
{
$('.NavSubhead', $(this)).hide();
}
);
});
``` | Jquery: When Hover on Menu Item, Display Text | [
"",
"javascript",
"jquery",
"css",
"navigation",
"hover",
""
] |
Most HTML in a large website is duplicated across pages (the header, footer, navigation menus, etc.). How do you design your code so that all this duplicate HTML is not actually duplicated in your code? For example, if I want to change my navigation links from a `<ul>` to a `<ol>`, I'd like to make that change in just one file.
Here's how I've seen one particular codebase handle this problem. The code for every page looks like this:
```
print_top_html();
/* all the code/HTML for this particular page */
print_bottom_html();
```
But I feel uncomfortable with this approach (partially because opening tags aren't in the same file as their closing tags).
**Is there a better way?**
I mostly work with PHP sites, but I'd be interested in hearing solutions for other languages (I'm not sure if this question is language-agnostic). | One solution at least in the case of PHP (and other programming languages) is templates. Instead of having two functions like you have above it would instead be a mix of HTML and PHP like this.
```
<html>
<head>
<title><?php print $page_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
</head>
<body>
<div id="nav">
<?php print $nav ?>
</div>
<div id="content">
<?php print $content ?>
</div>
</body>
</html>
```
Each variable within this template would contain HTML that was produced by another template, HTML produced by a function, or also content from a database. There are a number of [PHP template engines](http://www.google.com/search?q=php+template+engine) which operate in more or less this manner.
You create a template for HTML that you would generally use over and over again. Then to use it would be something like this.
```
<?php
$vars['nav'] = _generate_nav();
$vars['content'] = "This is the page content."
extract($vars); // Extracts variables from an array, see php.net docs
include 'page_template.php'; // Or whatever you want to name your template
```
It's a pretty flexible way of doing things and one which a lot of frameworks and content management systems use. | I'm not a php programmer, but I know we can use a templating system called Smarty that it works with templates(views), something like asp.net mvc does with Razor.
look here <http://www.smarty.net/> | How is duplicate HTML represented in your codebase, in a non-duplicate way? | [
"",
"php",
"codebase",
""
] |
My object is "MyClass" with 2 properties : Id (int) and HourBy (int)
I have two list :
```
var List1 = new List<MyClass>();
var List2 = new List<MyClass>();
```
I'd like to get one list with :
- Object from List1 present in List2 based on Id with Hourby (list2) < Hourby in List1
- Object from List1 no present in List2
```
//#Sample1
//List1 :
List1.add(new MyClass(1,10));
List1.add(new MyClass(2,20));
List1.add(new MyClass(3,30));
//List2 :
List2.add(new MyClass(1,10));
List2.add(new MyClass(2,15));
//I'd like to get :
new MyClass(2,5);
new MyClass(3,30);
//Sample2
List1 :
List1.add(new MyClass(1,10));
List1.add(new MyClass(2,20));
List1.add(new MyClass(3,30));
//List2 :
List2.add(new MyClass(1,10));
List2.add(new MyClass(2,15));
List2.add(new MyClass(2,2));
//I'd like to get :
new MyClass(2,3);
new MyClass(3,30);
```
Thanks, | I use this code, it's not perfect but working and may be clearer for newbie in Linq (like me)
```
List< MyClass> listRes = new List< MyClass>();
foreach ( MyClass item in list1)
{
var exist = list2
.Select(x => x.MyClass)
.Contains(item);
if (!exist)
listRes.Add(item);
else
{
var totalFromOther = list2
.Where(x => x.MyClass.Id == item.Id)
.Sum(y => y.HourBy);
if (item.HourBy != totalFromOther)
{
item.HourBy = item.HourBy - totalFromOther;
listRes.Add(item);
}
}
}
```
Thanks for you help, | You can do this by the following Linq statement:
```
var result = List1.Where(x => !List2.Select(y => y.Id).Contains(x.Id)
|| List2.Single(y => x.Id == y.Id).HourBy < x.HourBy);
```
Best Regards | Compare lists and get values with Linq | [
"",
"c#",
".net",
"linq",
""
] |
I am trying to debug C++ code using Eclipse Galileo on my MacBook Pro running [Mac OS X v10.5](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) (Leopard). It's my first time trying this. I have a complicated C++ program I'd like to debug, but to test things out, I just tried to debug and step through the following:
```
#include <iostream>
using namespace std;
int main()
{
int x = 0;
cout << x << endl;
x = 54;
cout << x << endl;
return 0;
}
```
I clicked the debug icon, told it to use [GDB](http://en.wikipedia.org/wiki/GNU_Debugger) (DSF) Create Process Launcher and started to step through the code. I wanted to be able to monitor the value of x, so I opened up the Variables window and watched. Initially, it was 4096 - presumably some garbage value. As soon as I hit the next line, where it had shown the value, it now shows the following error:
```
Failed to execute MI command:
-var-update 1 var1
Error message from debugger back end:
Variable object not found
```
I can't seem to figure this out or get around it. And a few Google searches turned up bone dry without even the hint of a lead.
---
**Solution**: As [drhirsch](https://stackoverflow.com/users/154980/drhirsch) pointed out below, use the Standard Create Process Launcher instead of the GDB Create Process Launcher. (This is actually a workaround and not a true solution, but it worked for at least two of us.) | In my experience the gdb/dsf launcher is still quite unusable. I can't get it to show variables too, it seems still very buggy.
Did you try the Standard Create Process Launcher? For me this works fine. | This appears to still be a problem without a reliably good answer, other than using an IDE other than Eclipse.
I tried both the DSF Create Process Launcher and the Standard Create Process Launcher variations, but neither results in a successful debugging experience. The GDB debugger launches either way, but breakpoints are not handled properly (unresolved in some cases) and almost no variable values can be inspected/tracked.
Here's what software I'm using:
* Eclipse 3.5.2 (Galileo), 64-bit Cocoa version
* Eclipse C/C++ development tools 6.0.2.2
* Mac OS X 10.6.3 (Snow Leopard)
* GDB 6.3.5 (Apple's version that ships with Xcode)
I've also tried building GDB 7.1 from source since as of 7.0 it is supposed to have native x86/x86\_64 Darwin support. It builds fine and launches OK from the command-line, but it has various problems when I try launching it from Eclipse. These appear to be related to changes that Apple made recently to how the taskgated mechanism works for allowing debuggers to connect to processes. The following error is typical of these:
```
Target request failed: Unable to find Mach task port for process-id 88283:
(os/kern) failure (0x5).\n (please check gdb is codesigned - see taskgated(8)).
```
Various sources on the web indicate that Apple uses their own special patches in GDB 6.3.5 to support Mac OS X, however this is a really old code base (2004). Conversely, other web sources indicate that the Eclipse DSF debugger framework requires GDB commands that only appear starting in GDB 6.6 (circa 2006?).
I've been all over the Eclipse-related forums but have found no signs of a solution to this problem. It appears that almost no one on the Eclipse CDT development team uses Mac OS X, so they rarely bother to test their changes on this platform.
**EDIT UPDATE**: In addition to the above, I've retried all of the prior described testing (GDB versions 6.3.5 and 7.1) with a developer build, Eclipse Helios 3.6 RC3 (IDE for C/C++ developers), which includes CDT 7.0. Encountered all of the same reported problems. **Eclipse CDT debugging on Mac OS X Snow Leopard is still non-functional.**
Does anyone know something different and/or a reliable Eclipse-based solution to the scenario I've reported above? | Trouble debugging C++ using Eclipse Galileo on Mac | [
"",
"c++",
"eclipse",
"macos",
"gdb",
"galileo",
""
] |
Can I install [Pinax](http://pinaxproject.com/) on Windows Environment?
Is there a easy way?
Which environment do you recommend? | I have pinax 0.7rc1 installed and working on windows 7, with no problems.
Check out this video for a great example on how to do this. He uses pinax 0.7beta3 on windows XP.
<http://www.vimeo.com/6098872>
Here are the steps I followed.
1. download and install python
2. download and install python image library
3. download pinax at <http://pinaxproject.com>
4. extract the download to some working directory `<pinax-directory>` (maybe c:\pinax ?)
5. make sure you have python in your path (c:\pythonXX)
6. make sure you have the python scripts folder in your path (c:\pythonXX\scripts)
7. open a command prompt
8. `cd` to `<pinax-directory>\scripts` folder
9. run `python pinax-boot.py <pinax-env>` (I used "../pinax-env")
10. wait for pinax-boot process to finish
-- technically pinax is installed and ready to use, but the next steps will get you up and running with pinax social app (any other app will also work fine)
11. cd to your `<pinax-env>\scripts` directory
12. execute the `activate.bat` script
13. execute `python clone_project social <pinax-env>\social`
14. cd to `<pinax-env>\social`
15. execute `python manage.py syncdb`
16. execute `python manage.py runserver`
17. open your browser to the server and you should see your new pinax site
Voila!! Pinax on Windows. | Provided you have Python and Django installed, Pinax should install fine. According to the documentation there is one step that you have to do specifically on Windows however (Under the "Note To Windows Users" heading):
<http://pinaxproject.com/docs/0.5.1/install.html> | Installing Pinax on Windows | [
"",
"python",
"django",
"web-applications",
"pinax",
""
] |
I have a complex ASP.NET page that makes heavy usage of jquery for DOM manipulation (no AJAX). The page is faster in Mozilla based browsers (Firefox) compared to IE 7 or 8.
Are there some functions that are optimized for FF? | The power is in the javascript processing engine. Unlike serverside processing (PHP, ASP.net), javascript is client side, meaning that your visitor's browser all have to do the work of rendering the page. Competitors try to get people to switch to their browser by boasting faster processing of things like javascript.
This leads to all the browsers having their own processing engines. Which leads to some browsers being slower. IE:
Internet Explorer doesn't use the Mozilla Engine, so it is considerably slower than Firefox. Internet Explorer is known as one of the slower engines out of all the major browsers.
Firefox is slower than Chrome, which boats one of the highest Javascript Engines (A Modified Version of Webkit).
Safari I believe is currently the fastest rendering engine out there.
You can see more stats on this article from [PCWorld](http://www.pcworld.com/article/168623/browser_speed_tests_latest_firefox_is_faster_but_not_as_fast_as_google_chrome.html), and [here](http://cybernetnews.com/browser-comparison-internet-explorer-firefox-chrome-safari-opera/) | Well, the JavaScript engine itself is faster in Firefox, so that would naturally extend to jQuery being faster.
```
Web Browser Average Runtime Relative
----------- --------------- --------
Safari 4.0.2 (530.19.1) 169 1x (fastest)
Chrome 2.0.172.33 349 2.1x slower
Firefox 3.5 377 2.2x slower
Opera 9.64 (10487) 442 2.6x slower
IE 8.0 771 4.6x slower
```
Source: <http://celtickane.com/labs/web-browser-javascript-benchmark/> | Why is Jquery slower in IE? | [
"",
"javascript",
"jquery",
"performance",
"internet-explorer",
""
] |
The root problem: I have an application which has been running for several months now. Users have been reporting that it's been slowing down over time (so in May it was quicker than it is now). I need to get some evidence to support or refute this claim. I'm not interested in precise numbers (so I don't need to know that a login took 10 seconds), I'm interested in trends - that something which used to take x seconds now takes of the order of y seconds.
The data I have is an audit table which stores a single row each time the user carries out any activity - it includes a primary key, the user id, a date time stamp and an activity code:
```
create table AuditData (
AuditRecordID int identity(1,1) not null,
DateTimeStamp datetime not null,
DateOnly datetime null,
UserID nvarchar(10) not null,
ActivityCode int not null)
```
(Notes: DateOnly (datetime) is the DateTimeStamp with the time stripped off to make group by for daily analysis easier - it's effectively duplicate data to make querying faster).
Also for the sake of ease you can assume that the ID is assigned in date time order, that is 1 will always be before 2 which will always be before 3 - if this isn't true I can make it so).
ActivityCode is an integer identifying the activity which took place, for instance 1 might be user logged in, 2 might be user data returned, 3 might be search results returned and so on.
Sample data for those who like that sort of thing...:
```
1, 01/01/2009 12:39, 01/01/2009, P123, 1
2, 01/01/2009 12:40, 01/01/2009, P123, 2
3, 01/01/2009 12:47, 01/01/2009, P123, 3
4, 01/01/2009 13:01, 01/01/2009, P123, 3
```
User data is returned (Activity Code 2) immediate after login (Activity Code 1) so this can be used as a rough benchmark of how long the login takes (as I said, I'm interested in trends so as long as I'm measuring the same thing for May as July it doesn't matter so much if this isn't the whole login process - it takes in enough of it to give a rough idea).
(Note: User data can also be returned under other circumstances so it's not a one to one mapping).
So what I'm looking to do is select the average time between login (say ActivityID 1) and *the first instance after that for that user on that day* of user data being returned (say ActivityID 2).
I can do this by going through the table with a cursor, getting each login instance and then for that doing a select to say get the minimum user data return following it for that user on that day but that's obviously not optimal and is slow as hell.
My question is (finally) - is there a "proper" SQL way of doing this using self joins or similar without using cursors or some similar procedural approach? I can create views and whatever to my hearts content, it doesn't have to be a single select.
I can hack something together but I'd like to make the analysis I'm doing a standard product function so would like it to be right. | ```
SELECT TheDay, AVG(TimeTaken) AvgTimeTaken
FROM (
SELECT
CONVERT(DATE, logins.DateTimeStamp) TheDay
, DATEDIFF(SS, logins.DateTimeStamp,
(SELECT TOP 1 DateTimeStamp
FROM AuditData userinfo
WHERE UserID=logins.UserID
and userinfo.ActivityCode=2
and userinfo.DateTimeStamp > logins.DateTimeStamp )
)TimeTaken
FROM AuditData logins
WHERE
logins.ActivityCode = 1
) LogInTimes
GROUP BY TheDay
```
This might be dead slow in real world though. | In Oracle this would be a cinch, because of analytic functions. In this case, LAG() makes it easy to find the matching pairs of activity codes 1 and 2 and also to calculate the trend. As you can see, things got worse on 2nd JAN and improved quite a bit on the 3rd (I'm working in seconds rather than minutes).
```
SQL> select DateOnly
2 , elapsed_time
3 , elapsed_time - lag (elapsed_time) over (order by DateOnly) as trend
4 from
5 (
6 select DateOnly
7 , avg(databack_time - prior_login_time) as elapsed_time
8 from
9 ( select DateOnly
10 , databack_time
11 , ActivityCode
12 , lag(login_time) over (order by DateOnly,UserID, AuditRecordID, ActivityCode) as prior_login_time
13 from
14 (
15 select a1.AuditRecordID
16 , a1.DateOnly
17 , a1.UserID
18 , a1.ActivityCode
19 , to_number(to_char(a1.DateTimeStamp, 'SSSSS')) as login_time
20 , 0 as databack_time
21 from AuditData a1
22 where a1.ActivityCode = 1
23 union all
24 select a2.AuditRecordID
25 , a2.DateOnly
26 , a2.UserID
27 , a2.ActivityCode
28 , 0 as login_time
29 , to_number(to_char(a2.DateTimeStamp, 'SSSSS')) as databack_time
30 from AuditData a2
31 where a2.ActivityCode = 2
32 )
33 )
34 where ActivityCode = 2
35 group by DateOnly
36 )
37 /
DATEONLY ELAPSED_TIME TREND
--------- ------------ ----------
01-JAN-09 120
02-JAN-09 600 480
03-JAN-09 150 -450
SQL>
```
Like I said in my comment I guess you're working in MSSQL. I don't know whether that product has any equivalent of LAG(). | How do I analyse time periods between records in SQL data without cursors? | [
"",
"sql",
""
] |
Surprise -- this is a perfectly valid query in MySQL:
```
select X, Y from someTable group by X
```
If you tried this query in Oracle or SQL Server, you’d get the natural error message:
```
Column 'Y' is invalid in the select list because it is not contained in
either an aggregate function or the GROUP BY clause.
```
So how does MySQL determine which Y to show for each X? It just picks one. From what I can tell, it just picks the first Y it finds. The rationale being, if Y is neither an aggregate function nor in the group by clause, then specifying “select Y” in your query makes no sense to begin with. Therefore, I as the database engine will return whatever I want, and you’ll like it.
There’s even a MySQL configuration parameter to turn off this “looseness”.
<http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_by>
This article even mentions how MySQL has been criticized for being ANSI-SQL non-compliant in this regard.
<http://www.oreillynet.com/databases/blog/2007/05/debunking_group_by_myths.html>
My question is: ***Why*** was MySQL designed this way? What was their rationale for breaking with ANSI-SQL? | I believe that it was to handle the case where grouping by one field would imply other fields are also being grouped:
```
SELECT user.id, user.name, COUNT(post.*) AS posts
FROM user
LEFT OUTER JOIN post ON post.owner_id=user.id
GROUP BY user.id
```
In this case the user.name will always be unique per user.id, so there is convenience in not requiring the user.name in the `GROUP BY` clause (although, as you say, there is definite scope for problems) | According to [this page](https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html) (the 5.0 online manual), it's for better performance and user convenience. | Why does MySQL allow "group by" queries WITHOUT aggregate functions? | [
"",
"mysql",
"sql",
"standards-compliance",
"ansi-sql",
""
] |
I'm currently using `FileWriter` to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?
```
fout = new FileWriter(
"Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();
``` | Pass `true` as a second argument to `FileWriter` to turn on "append" mode.
```
fout = new FileWriter("filename.txt", true);
```
[FileWriter usage reference](http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29) | From the [Javadoc](http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29), you can use the constructor to specify whether you want to append or not.
> public FileWriter(File file,
> boolean append)
> throws IOException
>
> Constructs a FileWriter object given a File object. If the second
> argument is true, then bytes will be
> written to the end of the file rather
> than the beginning. | Java FileWriter with append mode | [
"",
"java",
"filewriter",
""
] |
I am planning on having asynchronous file uploads. That is the file should be uploaded to a jsp or servlet and return something to the html/jsp page without reloading the original page. It should happen like an AJAX call. Is there any way to do it in AJAX or any other way to do it. | I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).
SWFUpload is a good start : <http://www.swfupload.org/documentation>
jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.
Also helpful and worth looking into is Apache's FileUpload : <http://commons.apache.org/fileupload/index.html> | The two common approaches are to submit the form to an [invisible iframe](https://web.archive.org/web/20201109023443/http://geekswithblogs.net/rashid/archive/2007/08/01/Create-An-Ajax-Style-File-Upload.aspx), or to use a Flash control such as [YUI Uploader](https://web.archive.org/web/20161220051147/https://developer.yahoo.com/yui/uploader/). You could also use Java instead of Flash, but this has a narrower install base.
(Shame about the layout table in the first example) | Asynchronous file upload (AJAX file upload) using jsp and javascript | [
"",
"javascript",
"ajax",
"jsp",
"file-upload",
"forms",
""
] |
I have an application that I have written for my application distributed throughout the company to send data to me through our Windows 2003 server (running IIS 6.0). Small text messages get through, but larger messages containing more data (about 20 KB) are not getting through.
I set the byte buffer to the TCP Client’s buffer size. I noticed that my data was being received on the server; however, it only looped through the receive routine once, and my large files were always exactly the size of the buffer size, or 8 KB on our server. In other words, my code only makes it through one loop before the server closes the socket connection.
Thinking there might be an issue with filling the whole buffer, I tried limiting my read/writes to just 1 KB but this only resulted in our server closing the socket after receiving 1 KB before closing the connection.
I send the server’s error message back to the client so I can view it. The specific error message that I receive from the client is:
> “Unable to write data to the transport
> connection: An established connection
> was aborted by the software in your
> host machine.”
I updated my server application so that the underlying TCP Socket would use “keep alives” with this line:
```
client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
```
Now, whenever I attempt sending a message, the client receives the error:
> “Unable to write data to the transport
> connection: An existing connection was
> forcibly closed by the remote host.”
Our Network Administrator has told me that he does not have a firewall or any ports blocked on our internal server.
Googling the errors, I found posts suggesting people try to telnet into the server. I used their directions to telnet into the server, but I am not sure what to make of the response:
> C:> telnet Welcome to Microsoft
> Telnet Client
>
> Escape Character is ‘CTRL+]’
>
> Microsoft Telnet> open cpapp 500
> Connecting To cpapp…
This is all I get. I never get an error, and Microsoft’s Telnet screen will eventually change to “Press any key to continue…” – I guess it times out, but my code is somehow able to connect.
I have tried other ports in code and through Telnet including 25, 80, and 8080. Telnet kicks out port 25, but my application seems to read the first loop no matter what port I tell it to run.
Here is my code that runs on the clients:
```
int sendUsingTcp(string location) {
string result = string.Empty;
try {
using (FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read)) {
using (TcpClient client = new TcpClient(GetHostIP, CpAppDatabase.ServerPortNumber)) {
byte[] riteBuf = new byte[client.SendBufferSize];
byte[] readBuf = new byte[client.ReceiveBufferSize];
using (NetworkStream ns = client.GetStream()) {
if ((ns.CanRead == true) && (ns.CanWrite == true)) {
int len;
string AOK = string.Empty;
do {
len = fs.Read(riteBuf, 0, riteBuf.Length);
ns.Write(riteBuf, 0, len);
int nsRsvp = ns.Read(readBuf, 0, readBuf.Length);
AOK = Encoding.ASCII.GetString(readBuf, 0, nsRsvp);
} while ((len == riteBuf.Length) && (-1 < AOK.IndexOf("AOK")));
result = AOK;
return 1;
}
return 0;
}
}
}
} catch (Exception err) {
Logger.LogError("Send()", err);
MessageBox.Show(err.Message, "Message Failed", MessageBoxButtons.OK, MessageBoxIcon.Hand, 0);
return -1;
}
}
```
Here is my code that runs on the server:
```
SvrForm.Server = new TcpListener(IPAddress.Any, CpAppDatabase.ServerPortNumber);
void Worker_Engine(object sender, DoWorkEventArgs e) {
BackgroundWorker worker = sender as BackgroundWorker;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.CompanyName);
if (Directory.Exists(path) == false) Directory.CreateDirectory(path);
Thread.Sleep(0);
string eMsg = string.Empty;
try {
SvrForm.Server.Start();
do {
using (TcpClient client = SvrForm.Server.AcceptTcpClient()) { // waits until data is avaiable
if (worker.CancellationPending == true) return;
client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
string location = Path.Combine(path, string.Format("Acp{0:yyyyMMddHHmmssff}.bin", DateTime.Now));
byte[] buf = new byte[client.ReceiveBufferSize];
try {
using (NetworkStream ns = client.GetStream()) {
if ((ns.CanRead == true) && (ns.CanWrite == true)) {
try {
int len;
byte[] AOK = Encoding.ASCII.GetBytes("AOK");
using (FileStream fs = new FileStream(location, FileMode.Create, FileAccess.Write)) {
do {
len = ns.Read(buf, 0, client.ReceiveBufferSize);
fs.Write(buf, 0, len);
ns.Write(AOK, 0, AOK.Length);
} while ((0 < len) && (ns.DataAvailable == true));
}
byte[] okBuf = Encoding.ASCII.GetBytes("Message Received on Server");
ns.Write(okBuf, 0, okBuf.Length);
} catch (Exception err) {
Global.LogError("ServerForm.cs - Worker_Engine(DoWorkEvent)", err);
byte[] errBuf = Encoding.ASCII.GetBytes(err.Message);
ns.Write(errBuf, 0, errBuf.Length);
}
}
}
}
worker.ReportProgress(1, location);
}
} while (worker.CancellationPending == false);
} catch (SocketException) {
// See MSDN: Windows Sockets V2 API Error Code Documentation for detailed description of error code
e.Cancel = true;
} catch (Exception err) {
eMsg = "Worker General Error:\r\n" + err.Message;
e.Cancel = true;
e.Result = err;
} finally {
SvrForm.Server.Stop();
}
}
```
Why doesn’t my application continue reading from the TCP Client? Have I neglected to set something that tells the Socket to stay open until I have finished? The server code never sees an exception because the TCP Client is never stopped, so I know there is no error.
Our Network Administrator has not received his Associates Degree yet, so if it turns out to be an issue with the Server, kindly be detailed in your description of how to resolve this, because we might not understand what you’re saying.
I apologize for this being so long, but I want to make sure you folks out there know what I'm doing - and maybe even gleam some information from my technique!
Thanks for helping!
~Joe | You should precede the sent content with the length of that content. Your loop assumes that all of the data is sent before the loop executes, when in reality your loop is executing as the data is sent. There will be times when there is no data waiting on the wire, so the loop terminates; meanwhile, content is still being sent across the wire. That's why your loop is only running once. | If I read your code correctly, you've basically got (sorry for the c-style - I'm not good with c#:
```
do
{
socket = accept();
read(socket, buffer);
}while(not_done);
```
If I'm correct, then it means you need... a little more in there. If you want it to be serialized, reading each upload in sequence, you'll want a second loop:
```
do
{
socket = accept();
do { read(socket, buffer); not_done_reading=...; } while (not_done_reading);
}while(not_done);
```
If you want to read multiple uploads simultaniously, you'll need something more like:
```
do
{
socket = accept();
if( !fork() )
{
do { read(socket, buffer); not_done_reading=...; } while (not_done_reading);
}
}while(not_done);
``` | TCP Client Connection | [
"",
"c#",
"tcp",
"stream",
""
] |
Whenever I use session variables in webparts in sharepoint the page doesn't load and i get an error. I was adviced to enable them because they may be disabled. Any clue? | By Default the Session State is Disabled in SharePoint. If you look at the Web.Config the you will see that as below.
```
<pages enableSessionState="false"
```
You can enable it there. Else you can Enable this at the Page Level. | THEN, you must go into your web application and add the same session state module to the IIS7 managed pipeline.
1.Open IIS 7 manager, and find your web application.
2.Double click "Modules" in the IIS section.
3.Click "Add Managed Module..." on the right hand pane.
4.In the Add Managed Module dialog, enter "SessionState" or something like that for the name, and choose the following item from the dropdown:
System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
After that, session state should be enabled for your web app/web service! | How to enable session variables in sharepoint? | [
"",
"c#",
"sharepoint",
"session-variables",
""
] |
If I add let's say 1 line at the beggining of a method, if I set a breakpoint through Visual Studio on the first line, will it point to the first line or the second? If it will flag the wrong line, is there anything we could do when editing .exe files to ensure a regular debugging session later?
Isn't there something like setting line x to be Y? I remember seeing something like that somewhere, not sure if .NET related or not. | You'll need to update the debugging symbols in the PDB file if you want the debugging experience to remain unchanged.
The best option for this I've seen is to use [Mono.Cecil](http://www.mono-project.com/Cecil), as it supports (limited) modification of the debugging symbols as well as the IL. | If you are modifying IL then the PDB files will contain outdated information. Note that there probably won't be a 1:1 between changes in IL lines to the C# line #s (eg inserting 3 IL statements won't offset the IDE breakpoint by 3 lines of C#).
You may want to separate the IL-modified portions of your code into separate methods to minimize the impact. Also, assuming you are the one doing the IL modification, you may find it convenient to switch between the C# & IL views while debugging.
You might need to muck a bit with the generated code to facilitate that. For example, if the injected IL can be in a wrapper method then you could tell the debugger to ignore it by usage of attrbiutes such as DebuggerStepThroughAttribute, DebuggerNonUserCodeAttribute, or DebuggerHiddenAttribute. (Look up the documentation for the nuances in behavior) | What happens if we add lines to IL code and add breakpoints to our program? | [
"",
"c#",
".net",
"vb.net",
"intermediate-language",
""
] |
Sorry, I'm not sure how to phrase that and I'm really not very good with SQL. The db engine i SQL Server Compact. I currently have this query:
```
SELECT *
FROM Samples
WHERE FunctionId NOT IN
(SELECT CalleeId FROM Callers)
ORDER BY ThreadId, HitCount DESC
```
Which gives me:
```
ThreadId Function HitCount
1 164 6945
1 3817 1
4 1328 7053
```
Now, I only want the result with the maximum hit count for each unique value of Thread. In other words, that second row should be dropped. I'm not sure how to pull this off.
[EDIT] If it helps, this is an alternate form of the same query:
```
SELECT *
FROM Samples s1
LEFT OUTER JOIN Callers c1
ON s1.ThreadId = c1.ThreadId AND s1.FunctionId = c1.CalleeId
WHERE c1.ThreadId IS NULL
ORDER BY ThreadId
```
[EDIT] I ended up making schema changes to avoid doing this, as the suggested queries were looking rather expensive. Thanks for all the help. | Does SQL Server compact support windowed functions?
Alternative 1--Will include all rows that tie. Will not include a row, if the only rows for a given Thread all have null for HitCount:
```
SELECT Thread, Function, HitCount
FROM (SELECT Thread, Function, HitCount,
MAX(HitCount) over (PARTITION BY Thread) as MaxHitCount
FROM Samples
WHERE FunctionId NOT IN
(SELECT CalleeId FROM Callers)) t
WHERE HitCount = MaxHitCount
ORDER BY ThreadId, HitCount DESC
```
Alternative 2--Will include all rows that tie. If there is no row for a given thread with non-null HitCount, will return all rows for that thread:
```
SELECT Thread, Function, HitCount
FROM (SELECT Thread, Function, HitCount,
RANK() over (PARTITION BY Thread ORDER BY HitCount DESC) as R
FROM Samples
WHERE FunctionId NOT IN
(SELECT CalleeId FROM Callers)) t
WHERE R = 1
ORDER BY ThreadId, HitCount DESC
```
Alternative 3--Will non-determistically pick one row in case of ties and discard others. Will include a row if all rows for a given thread have null HitCount
```
SELECT Thread, Function, HitCount
FROM (SELECT Thread, Function, HitCount,
ROW_NUMBER() over (PARTITION BY Thread ORDER BY HitCount DESC) as R
FROM Samples
WHERE FunctionId NOT IN
(SELECT CalleeId FROM Callers)) t
WHERE R = 1
ORDER BY ThreadId, HitCount DESC
```
Alternative 4 & 5--Uses older constructs, if the windowed functions aren't available, and says what is meant a little cleaner than using joins. Benchmark if spead is a priority. Both return all rows that participate in a tie. Alternative 4 will HitCount is null when non-null values are not available for HitCount. Alternative 5 will not return rows with HitCount is null.
```
SELECT *
FROM Samples s1
WHERE FunctionId NOT IN
(SELECT CalleeId FROM Callers)
AND NOT EXISTS
(SELECT *
FROM Samples s2
WHERE s1.FunctionId = s2.FunctionId
AND s1.HitCount < s2.HitCount)
ORDER BY ThreadId, HitCount DESC
SELECT *
FROM Samples s1
WHERE FunctionId NOT IN
(SELECT CalleeId FROM Callers)
AND HitCount =
(SELECT MAX(HitCount)
FROM Samples s2
WHERE s1.FunctionId = s2.FunctionId)
ORDER BY ThreadId, HitCount DESC
``` | Here's how I would do it:
```
SELECT s1.*
FROM Samples s1
LEFT JOIN Samples s2
ON (s1.Thread = s2.Thread and s1.HitCount < s2.HitCount)
WHERE s1.FunctionId NOT IN (SELECT CalleeId FROM Callers)
AND s2.Thread IS NULL
ORDER BY s1.ThreadId, s1.HitCount DESC
```
In other words, the row `s1` for which there is no other row `s2` matching the same `Thread` and having a greater `HitCount`. | SQL: Select maximum value for each unique key? | [
"",
"sql",
"sql-server",
"database",
""
] |
I notice the thread of similar question: [Limit size of Queue<T> in .NET?](https://stackoverflow.com/questions/1292/limit-size-of-queuet-in-net)
That's exactly what I want to do, but I am not using .net but GNU C++. I have no reference to the base class in GNU C++, so java like `super.***()` or .net like `base.***()` will not work. I have been trying to inherit from queue class but it turns out in vain.
What I want to do:
specify the size of the queue, and automatically dequeue when the queue is full. To be specific: if the maximum size of my queue is 2, when I push the 3rd item, the 1st item will be automatically popped out before pushing the new item.
How to implement such a queue?
Thanks. | Make a new class that encapsulates the queue and enforce a size limit in the new class. | I know you said "automatic", but, to keep things simple: Encapsulate just the `Enqueue()`ing in a local function (no, not clean OO, but it works):
```
Queue<T> myQueue = new Queue<T>();
void addToMyQueue(T param)
{
myQueue.Enqueue(param); //or push(param)
if (myQueue.Count > LIMIT)
myQueue.Dequeue(); //or pop()
}
void main()
{
addToMyQueue(param);
}
``` | limit size of Queue<T> in C++ | [
"",
"c++",
"queue",
"limit",
"containers",
""
] |
Does List.Contains(mystring) do a reference comparison or a value comparison?
Eg I have this code:
```
/// <summary>
/// If the value isn't null or an empty string,
/// and doesn't exist in the list, it adds it to the list
/// </summary>
static void AddToListIfNotEmpty(List<string> thelist, SqlString val)
{
string value = val.ToString().Trim();
if (!string.IsNullOrEmpty(value))
{
bool found = false;
foreach (string x in thelist) if (x == value) found = true;
if (!found) thelist.Add(value);
}
}
```
Can i simplify the foreach and following line to:
```
if (!thelist.Contains(value)) thelist.Add(value);
```
Thanks | `IList<T>` uses `Comparator<T>.Default` to do the comparisons, and in turn that compares by value for `String` objects.
If you wanted to, you could move your items to an `IDictionary<T, bool>` or something similar, where you can specify your `IComparator` - specifying one that checks for reference. (even though in that case, you're better off with the foreach loop)
If you can use LINQ, you could create a statement there with a reference comparison, too. | From [MSDN](http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx) of `List<T>.Contains`
> This method determines equality using
> the default equality comparer
> `EqualityComparer<T>.Default` for T,
> the type of values in the list.
>
> ...
> The Default property checks
> whether type T implements the
> `IEquatable<T>` generic interface and
> if so returns an `EqualityComparer<T>`
> that uses that implementation.
> Otherwise it returns an
> `EqualityComparer<T>` that uses the
> overrides of `Object.Equals` and
> `Object.GetHashCode` provided by `T`.
Looking at reflector (and by the principle of least surprise), String Equality has value type semantics - so they are equal if they have the same strings. Both `Equals(Object)` and `IEquatable.Equals(T)` delegate to `String::EqualsHelper` | Does List<String>.Contains(mystring) do a reference comparison or a value comparison? | [
"",
"c#",
"string",
""
] |
Easy one for you guys.
I have a textbox on top of a listbox.
The textbox is use to filter ther data in the listbox.
So... When the user type in the textbox, I would like to "trap" the down/up/pagedown/pageup keystrokes and fowarding them to the listbox.
I know I could use the Win32 API and send the WM\_KeyDown message. But there's must be some .NET way to do this. | SendKeys.Send() Method.
```
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
listBox1.Focus();
SendKeys.Send(e.KeyChar.ToString());
}
```
Here is code through which you can select a list item.
```
private void Form1_Load(object sender, EventArgs e)
{
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource=AutoCompleteSource.CustomSource;
string[] ar = (string[])(listBox1.Items.Cast<string>()).ToArray<string>();
textBox1.AutoCompleteCustomSource.AddRange(ar);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox1.Text = textBox1.Text;
}
``` | ```
private void textBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.PageUp || e.KeyCode == Keys.PageDown || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
// Setting e.IsInputKey to true will allow the KeyDown event to trigger.
// See "Remarks" at https://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx
e.IsInputKey = true;
}
}
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
string send = "";
if (e.KeyCode == Keys.PageUp)
{
send = "PGUP";
}
else if (e.KeyCode == Keys.PageDown)
{
send = "PGDN";
}
else if (e.KeyCode == Keys.Up)
{
send = "UP";
}
else if (e.KeyCode == Keys.Down)
{
send = "DOWN";
}
if (send != "")
{
// We must focus the control we want to send keys to and use braces for special keys.
// For a list of all special keys, see https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx.
listBox.Focus();
SendKeys.SendWait("{" + send + "}");
textBox.Focus();
// We must mark the key down event as being handled if we don't want the sent navigation keys to apply to this control also.
e.Handled = true;
}
}
``` | Send keystroke to other control | [
"",
"c#",
"forwarding",
"keystroke",
""
] |
i am trying to set transparency of all windows. I have following code.
```
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
public const int GWL_EXSTYLE = -20;
public const int WS_EX_LAYERED = 0x80000;
public const int LWA_ALPHA = 0x2;
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
SetWindowLong(theprocess.Handle, GWL_EXSTYLE,
GetWindowLong(theprocess.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED);
SetLayeredWindowAttributes(theprocess.Handle, 0, 128, LWA_ALPHA);
}
}
}
```
nothing happens when I execute the code.
What is wrong?? | `SetWindowLong` takes a window handle (hWnd), but you're passing it a process handle instead.
Change all instances of
```
theprocess.Handle
```
to
```
theProcess.MainWindowHandle
```
After changing that, it worked on the Windows XP machine I tested it on. Now I'm gonna have to modify the code to get the windows back to normal ;) Luckily, the Visual Studio 2010 window was unaffected. | This part of your code: `^ WS_EX_LAYERED` flips the WS\_EX\_LAYERED bit,
I think you want: `| WS_EX_LAYERED` | can't I set transparency of a window by its handle in c#? | [
"",
"c#",
"transparency",
"handle",
""
] |
What are the best practices or pit falls that we need to be aware of when using Microsoft Oracle provider in a web service centric .NET application? | Some practices we employ based on our production experience:
* Validate connections when retrieving them from the connection pool.
* Write your service code to not assume that connections are valid - failure to do so can cause quite a bit of grief especially in production environments
* Wherever possible, explicitly close and dispose connections after using them (`using(conn){}` blocks work well)
* In a service, you should use connections for the shortest time possible - particularly if you are looking to create a scalable solution.
* Consider using explicit timouts on requests appropriate to the typical duration of a request. The last thing you want is to have one type of request that hangs to potentially block your whole system.
* Wherever possible use bind variables to avoid hard parses at the database (this can be a performance nightmare if you don't start out with this practice). Using bind variables also protect you from basic SQL-injection attacks.
* Make sure you have adequate diagnostic support built into your system - consider creating a wrapper around the Oracle ADO calls so that you can instrument, log, and locate all of them.
* Consider using stored procedures or views when possible to push query semantics and knowledge of the data model into the database. This allows easier profileing and query tuning.
* Alternatively, consider use a good ORM library (EF, Hibernate, etc) to encapsulate data access - particularly if you perform both read and write operations.
* Extending on the above - don't pepper your code with dozens of individually written SQL fragments. This quickly becomes a maintainability nightmare.
* If you are committed to Oracle as a database, don't be afraid to use Oracle-specific features. The ODP library provides access to most features - such as returning table cursors, batch operations, etc.
* Oracle treats empty strings ("") and NULLs as equivalent - .NET does not. Normalize your string treatment as appropriate for Oracle.
* Consider using NVARCHAR2 instead of VARCHAR2 if you will store Unicode .NET string directly in your database. Otherwise, convert all unicode strings to conform to the core ASCII subset. Failure to do so can cause all sorts of confusing and evil data corruption problems. | Some more tips:
* Avoid using Microsoft Oracle provider because it goes out of support (<http://blogs.msdn.com/adonet/archive/2009/06/15/system-data-oracleclient-update.aspx>)
* If you're commited to Oracle use oracle specific features and link Oracle.DataAccess assembly to your code
* If you're not sure and want to be flexible, use System.Data.Common classes and load oracle provider through | Best practices when using oracle DB and .NET | [
"",
"c#",
".net",
"asp.net",
"oracle",
""
] |
I wanted to ask you what is the best approach to implement a cache in C#? Is there a possibility by using given .NET classes or something like that? Perhaps something like a dictionary that will remove some entries, if it gets too large, but where whose entries won't be removed by the garbage collector? | If you're using ASP.NET, you could use the `Cache` class (`System.Web.Caching`).
Here is a good helper class: [c-cache-helper-class](http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/)
If you mean caching in a windows form app, it depends on what you're trying to do, and where you're trying to cache the data.
We've implemented a cache behind a Webservice for certain methods
(using the `System.Web.Caching` object.).
However, you might also want to look at the Caching Application Block. ([See here)](http://msdn.microsoft.com/en-us/library/cc339057.aspx) that is part of the Enterprise Library for .NET Framework 2.0. | If you are using .NET 4 or superior, you can use [MemoryCache](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache?view=netframework-4.8.1) class. | Caching in C#/.Net | [
"",
"c#",
".net",
"caching",
""
] |
I'm trying to figure a way to create a generic class for number types only, for doing some calculations.
Is there a common interface for all number types (int, double, float...) that I'm missing???
If not, what will be the best way to create such a class?
**UPDATE:**
The main thing I'm trying to achieve is checking who is the bigger between two variables of type T. | What version of .NET are you using? If you are using .NET 3.5, then I have a [generic operators implementation](https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html) in [MiscUtil](https://jonskeet.uk/csharp/miscutil/) (free etc).
This has methods like `T Add<T>(T x, T y)`, and other variants for arithmetic on different types (like `DateTime + TimeSpan`).
Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.
Some additional background on why this is tricky is [here](https://jonskeet.uk/csharp/genericoperators.html).
You may also want to know that `dynamic` (4.0) sort-of solves this issue indirectly too - i.e.
```
dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect
```
---
Re the comment about `<` / `>` - you don't actually *need* operators for this; you just need:
```
T x = ..., T y = ...
int c = Comparer<T>.Default.Compare(x,y);
if(c < 0) {
// x < y
} else if (c > 0) {
// x > y
}
``` | There are interfaces for some of the operations on the number types, like the `IComparable<T>`, `IConvertible` and `IEquatable<T>` interfaces. You can specify that to get a specific functionality:
```
public class MaxFinder<T> where T : IComparable<T> {
public T FindMax(IEnumerable<T> items) {
T result = default(T);
bool first = true;
foreach (T item in items) {
if (first) {
result = item;
first = false;
} else {
if (item.CompareTo(result) > 0) {
result = item;
}
}
}
return result;
}
}
```
You can use delegates to expand a class with type specific operations:
```
public class Adder<T> {
public delegate T AddDelegate(T item1, T item2);
public T AddAll(IEnumerable<T> items, AddDelegate add) {
T result = default(T);
foreach (T item in items) {
result = add(result, item);
}
return result;
}
}
```
Usage:
```
Adder<int> adder = new Adder<int>();
int[] list = { 1, 2, 3 };
int sum = adder.AddAll(list, delegate(int x, int y) { return x + y; });
```
You can also store delegates in the class, and have different factory methods that sets up delegates for a specific data type. That way the type specific code is only in the factory methods. | Generics - where T is a number? | [
"",
"c#",
"generics",
"numbers",
""
] |
What is a way to simply wait for all threaded process to finish? For example, let's say I have:
```
public class DoSomethingInAThread implements Runnable{
public static void main(String[] args) {
for (int n=0; n<1000; n++) {
Thread t = new Thread(new DoSomethingInAThread());
t.start();
}
// wait for all threads' run() methods to complete before continuing
}
public void run() {
// do something here
}
}
```
How do I alter this so the `main()` method pauses at the comment until all threads' `run()` methods exit? Thanks! | You put all threads in an array, start them all, and then have a loop
```
for(i = 0; i < threads.length; i++)
threads[i].join();
```
Each join will block until the respective thread has completed. Threads may complete in a different order than you joining them, but that's not a problem: when the loop exits, all threads are completed. | One way would be to make a `List` of `Thread`s, create and launch each thread, while adding it to the list. Once everything is launched, loop back through the list and call `join()` on each one. It doesn't matter what order the threads finish executing in, all you need to know is that by the time that second loop finishes executing, every thread will have completed.
A better approach is to use an [ExecutorService](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) and its associated methods:
```
List<Callable> callables = ... // assemble list of Callables here
// Like Runnable but can return a value
ExecutorService execSvc = Executors.newCachedThreadPool();
List<Future<?>> results = execSvc.invokeAll(callables);
// Note: You may not care about the return values, in which case don't
// bother saving them
```
Using an ExecutorService (and all of the new stuff from Java 5's [concurrency utilities](http://java.sun.com/j2se/1.5.0/docs/guide/concurrency/)) is incredibly flexible, and the above example barely even scratches the surface. | How to wait for a number of threads to complete? | [
"",
"java",
"multithreading",
"parallel-processing",
"wait",
""
] |
How do you extract the Web Site name from a URL or a Link. I have found examples for other languages but not c#. Also the URL / Link will not be the current page that i am on.
e.g. <http://www.test.com/SomeOther/Test/Test.php?args=1>
From that i need to extract just www.test.com , keep in mind that it wont always be .com and it can be any domain | How about:
```
new Uri(url).Host
```
For example:
```
using System;
class Test
{
static void Main()
{
Uri uri = new Uri("http://www.test.com/SomeOther/Test/Test.php?args=1");
Console.WriteLine(uri.Host); // Prints www.test.com
}
}
```
Check out the docs for the [constructor taking a string](http://msdn.microsoft.com/en-us/library/z6c2z492.aspx) and [the `Host` property](http://msdn.microsoft.com/en-us/library/system.uri.host.aspx).
Note that if it's not a "trusted" data source (i.e. it could be invalid) you might want to use [Uri.TryCreate](http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx):
```
using System;
class Test
{
static void Main(string[] args)
{
Uri uri;
if (Uri.TryCreate(args[0], UriKind.Absolute, out uri))
{
Console.WriteLine("Host: {0}", uri.Host);
}
else
{
Console.WriteLine("Bad URI!");
}
}
}
``` | ```
this.Request.Url.Host
```
The other properties in this class will be of interest. | Extract Web Site name from url | [
"",
"c#",
".net",
""
] |
I have the following, it works except the gif is suppose to be transparent and it is creating a black background, if I change all the (imagesavealpha, etc) stuff to the $container then it created a transparent background for the text I add to this image. How would I go about getting rid of the black background? Basically this is a signature type image. I write stuff too, which I don't think you need to see.
```
$im = imagecreatefromgif("bg.gif");
$container = imagecreatetruecolor(400, 160);
imagesavealpha($im, true);
imagealphablending($im, false);
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
$w = imagecolorallocate($container, 255, 255, 255);
imagefill($im, 0, 0, $trans_colour);
imagecopymerge($container, $im, 0, 0, 0, 0, 460, 180, 100);
``` | I use these two functions to allow you to create a new transparent truecolour image...
```
function image_createtruecolortransparent($x,$y)
{
$i = imagecreatetruecolor($x,$y);
$b = imagecreatefromstring(base64_decode(image_blankpng()));
imagealphablending($i,false);
imagesavealpha($i,true);
imagecopyresized($i,$b,0,0,0,0,$x,$y,imagesx($b),imagesy($b));
return $i;
}
function image_blankpng()
{
$c = "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29m";
$c .= "dHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADqSURBVHjaYvz//z/DYAYAAcTEMMgBQAANegcCBNCg";
$c .= "dyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAAN";
$c .= "egcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQ";
$c .= "oHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAA";
$c .= "DXoHAgTQoHcgQAANegcCBNCgdyBAgAEAMpcDTTQWJVEAAAAASUVORK5CYII=";
return $c;
}
```
Which should do what you need. Just replace your function call to imagecreatetruecolor(400, 160); with image\_createtruecolortransparent(400, 160); and include both functions. | The solution below is less complicated than the one you chose. It also addresses the question directly.
```
$transparencyIndex = imagecolortransparent($imageSrc);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
```
if ($transparencyIndex >= 0) {
$transparencyColor = imagecolorsforindex($imageSrc, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate(
$imageNew, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']
);
imagefill($imageNew, 0, 0, $transparencyIndex);
imagecolortransparent($imageNew, $transparencyIndex);
To resize and store the GIF image, imagecopyresampled() and imagegif() could be respectively used. | Transparent gif/black background? | [
"",
"php",
"transparency",
""
] |
The result of all of the division equations in the below for loop is 0. How can I get it to give me a decimal e.g.:
```
297 / 315 = 0.30793650793650793650793650793651
```
Code:
```
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100;
long result2 = i / 100;
double result3 = i / 100;
float result4 = i / 100;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})", i, 100, i / 100, result, result2, result3, result4);
}
Console.ReadLine();
}
}
}
```
# Answer:
Thanks Jon and everyone, this is what I wanted to do:
```
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
int maximum = 300;
for (int i = 0; i <= maximum; i++)
{
float percentage = (i / (float)maximum) * 100f;
Console.WriteLine("on #{0}, {1:#}% finished.", i, percentage);
}
Console.ReadLine();
}
}
}
``` | You're using int/int, which does everything in integer arithmetic even if you're assigning to a decimal/double/float variable.
Force one of the operands to be of the type you want to use for the arithmetic.
```
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100m;
long result2 = i / 100;
double result3 = i / 100d;
float result4 = i / 100f;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})",
i, 100, i / 100d, result, result2, result3, result4);
}
```
Results:
```
0/100=0 (0,0,0, 0)
1/100=0.01 (0.01,0,0.01, 0.01)
2/100=0.02 (0.02,0,0.02, 0.02)
3/100=0.03 (0.03,0,0.03, 0.03)
4/100=0.04 (0.04,0,0.04, 0.04)
5/100=0.05 (0.05,0,0.05, 0.05)
```
(etc)
Note that that *isn't* showing the exact value represented by the float or the double - you *can't* represent 0.01 exactly as a float or double, for example. The string formatting is effectively rounding the result. See my [article on .NET floating binary point](http://pobox.com/~skeet/csharp/floatingpoint.html) for more information as well as a class which will let you see the *exact* value of a double.
I haven't bothered using 100L for `result2` because the result would always be the same. | Try
```
i / 100.0
``` | Why do these division equations result in zero? | [
"",
"c#",
"types",
"numerical",
""
] |
my problem is the following. I wrote a class AJAXEngine, which creates in the constructor a new XMLHttpRequest object. The class contains a method called responseAnalyser, which is called when the "onreadystatechange" of the XMLHttpRequest object has changed.
So now I created lets say 4 instances of AJAXEngine => 4 XMLHttpRequest objects.
Now I have another class DataRequester, which has an array-attribute dataReq, which holds the instances of AJAXEngine. There is only one instance of DataReqeuster in the whole program!
DataRequester has a function called callWhenFinished. The function is called, by the function
responseAnalyser of AJAXEngine and decrements a variable of the DataRequester instance.
But, I think there happen race conditions. How could I prefent them in JavaScript?
```
function AJAXEngine
{
this.httpReqObj = //create new XMLHttpRequest Object
this.obj;
this.func;
}
AJAXEngine.prototype.responseAnalyser = function()
{
if(this.httpReqObj.readState == 4)
{
this.func.call(this.obj);
}
}
AJAXEngine.prototype.fireReq = function(o, f)
{
this.obj = o;
this.func = f;
// fire ajax req
}
function DataRequester()
{
this.dataReq = new Array();
this.test = 4;
for(var i = 0; i < 4; i ++)
{
this.dataReq[i] = new AJAXEngine();
}
}
DataRequester.prototype.callWhenFinished = function()
{
this.test --;
}
``` | Not sure if this would help, but it looks like you're trying to create a managed connection pool. I did one a few years ago that still works fine here:
[DP\_RequestPool Library](http://www.depressedpress.com/Content/Development/JavaScript/Extensions/DP_RequestPool/Index.cfm#Method_isBusy)
The pool ensures that requests are made in the order you've provided them (although, of course, they may be returned in any order based on performance) using as many simultaneous requests as you define (subject to system limitations). You can instantiate multiple pools for different purposes.
If nothing else this might give you some ideas. | You would need to implement a makeshift mutex (the idea is that a heuristic would check for a bool and set it to true if it's false then do body, otherwise sleep(settimeout?) - this is obviously a pretty bad heuristic that nobody would implement as it is not thread safe, but that's the general concept of how you would deal with the race conditions anyway).
I believe there at least one example of creating a mutex on the web, but I have not looked over it in detail - it has some detractors, but I am unaware of another way to achieve 'thread safety' in javascript. I haven't ever needed to implement js 'thread-safety', but that's I start looking if I had to deal with race conditions in javascript. | Race Condition because of multiple AJAX requests | [
"",
"javascript",
"ajax",
"xmlhttprequest",
"race-condition",
""
] |
How can I get the current Windows' browser proxy setting, as well as set them to a value?
I know I can do this by looking in the registry at `Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer`, but I'm looking, if it is possible, to do this without messing directly with the registry. | urllib module automatically retrieves settings from registry when no proxies are specified as a parameter or in the environment variables
> In a Windows environment, if no proxy
> environment variables are set, proxy
> settings are obtained from the
> registry’s Internet Settings section.
See the documentation of urllib module referenced in the earlier post.
To set the proxy I assume you'll need to use the pywin32 module and modify the registry directly. | If the code you are using uses `urlopen` under the hood you an set the `http_proxy` environment variable to have it picked up.
See the [documentation](http://docs.python.org/library/urllib.html) here for more info. | How to set proxy in Windows with Python? | [
"",
"python",
"windows",
"proxy",
"registry",
""
] |
I've got a list of elements and I want to use the header divs to separate them after the pages loaded up. So the code below,
```
<div class="header">Header 1</div>
<div class='test'>Test 1</div>
<div class='test'>Test 2</div>
<div class='test'>Test 3</div>
<div class="header">Header 2</div>
<div class='test'>Test 4</div>
<div class='test'>Test 5</div>
<div class='test'>Test 6</div>
<div class='test'>Test 7</div>
<div class='test'>Test 8</div>
<div class="header">Header 3</div>
<div class='test'>Test 9</div>
<div class='test'>Test 10</div>
<div class='test'>Test 11</div>
<div class='test'>Test 12</div>
<div class="header">Header 4</div>
<div class='test'>Test 13</div>
<div class='test'>Test 14</div>
```
Would become,
```
<div class='wrap'>
<div class="header">Header 1</div>
<div class='test'>Test 1</div>
<div class='test'>Test 2</div>
<div class='test'>Test 3</div>
</div>
<div class='wrap'>
<div class="header">Header 2</div>
<div class='test'>Test 4</div>
<div class='test'>Test 5</div>
<div class='test'>Test 6</div>
<div class='test'>Test 7</div>
<div class='test'>Test 8</div>
</div>
<div class='wrap'>
<div class="header">Header 3</div>
<div class='test'>Test 9</div>
<div class='test'>Test 10</div>
<div class='test'>Test 11</div>
<div class='test'>Test 12</div>
</div>
<div class='wrap'>
<div class="header">Header 4</div>
<div class='test'>Test 13</div>
<div class='test'>Test 14</div>
</div>
```
Any ideas? Thanks in advance. | What you are asking to do is **a terrible idea**. That's the kind of stuff you should do server-side. (There are always exceptions).
That being said, the following code should do what you ask.
```
$('.header').each(function() {
var head = $(this);
if(!head.parent().hasClass('wrap')) {
head.before('div class="wrap"></div>');
var wrap = head.prev();
var curr = head;
do {
var currEl = curr;
curr = curr.next();
currEl.appendTo(wrap);
} while(curr.length > 0 && !curr.hasClass('header'));
}
});
```
**NOTE:**
I do not usually develop in jQuery, so sorry if I don't follow whatever the standard way of doing jQuery is. | As of jQuery v1.4 you can use the [`nextUntil()`](http://api.jquery.com/nextUntil/) method, allowing you to do something like this:
```
var split_at = 'div.header';
$(split_at).each(function() {
$(this).add($(this).nextUntil(split_at)).wrapAll("<div class='wrap'/>");
});
``` | Use jQuery to wrap around groups of elements | [
"",
"javascript",
"jquery",
"html",
"css",
"dom",
""
] |
I've been looking around and came across the WT toolkit, Is it stable? Any good?
I was stumped on how to go about this in C++, given the lack of libraries and resources concerning web developement. (CGI/Apache)
The purpose of my application is to populate some data from a Sybase ASE15 database running GNU/Linux & Apache Hence allow some user interactions.
I am going to use Sybase open client library (libct) to retrieve columns from the Server, feed this data back to wt model/view.
My requests:
Is there any more practical solution rather than using other scripting languages?
I mean by practical, an interface with ODBC retrieving, and MVC mechanism?
If not available in C++, any alternative in Java? | Give this one a look. I never much liked Wt's design. But then, I'm kind of an anti-framework guy.
<http://cppcms.sourceforge.net/wikipp/en/page/main> | > C++ isn't a very popular choice for
> web applications - probably because
> it's too easy to leave security holes,
> and development time tends to be a lot
> slower than for the scripting
> languages.
Dynamically typed scripting languages convert compile-time errors to runtime errors. Detecting those might not be as easy as reading through the compiler output. Scripting languages may be OK for quick-and-dirty simple projects. Beyond a certain level of complexity one needs strongly typed, well-structured languages. Such as C++, or Java.
Most scripting languages encourage sloppy programming.
As to the "security holes": if you refer to buffer overruns, allocation/deallocation errors, the answer is "STL". And proper training of course :-) | Any good C/C++ web toolkit? | [
"",
"c++",
"apache",
"cgi",
""
] |
We run a C# console application that starts multiple threads to do work. The main function looks something like this:
```
try
{
DoWork();
}
catch (Exception err)
{
Logging.Log("Exception " + err.ToString());
}
Logging.Log("Finished");
```
The `DoWork()` function reads new jobs from a database, and spawns threads to process one work item each. Since last week, the application has started disappearing mysteriously. It disappears from the processes list and there is no entry in the event logs. The log file shows work up to a certain point: it does not log an exception, or the "Finished" line.
Any clue(s) on how a C# application can vanish like that?
EDIT: Threads are created like:
```
new Thread(SomeObj.StartFunc).Start();
```
Some of the disappearances occur when no threads are running.
P.S. We installed DebugDiag with a rule to create a crash dump whenever our program crashed. It did not create any dump files when the process disappeared. | What's the identity that you're using to run the console application?
Also, you might want to use SetConsoleCtrlHandler to capture the console events. Look at [this blog post](http://www.hanselman.com/blog/MoreTipsFromSairamaCatchingCtrlCFromANETConsoleApplication.aspx) for more details. We had a similar issue when the console application was run under a service account, and it would occasionally get terminated. I'm not sure if this is what you're running into. Let me know I can post some code.
UPDATE: It looks like your scenario resembles what we had experienced. In your console event handler, you need to check for the *LogOff* event and return true. Look at [this KB article](http://support.microsoft.com/kb/149901).
```
public static void inputHandler(ConsoleCtrl.ConsoleEvent consoleEvent)
{
if (ConsoleEvent == ConsoleCtrl.ConsoleEvent.CtrlLogOff)
return true;
return false;
}
``` | You need to have a similar catch block at the top level of the function that every thread works. If there is an uncaught exception on a thread it will kill the application, and the catch block on the main thread is not going to help. | C# application terminates unexpectedly | [
"",
"c#",
".net",
""
] |
I have only created regular windows applications (C# mostly). What differentiates a windows service from a regular windows application? What makes them different? What can a service do that an application can't? What are the differences seen from a developers point of view? How do you create one? Is it just to create a regular application (Console application maybe, since there are no gui?) and run or install it in a special way, or is it more that has to be done? | There are a couple of things that jump out to me immediately.
* They run in an entirely different console starting with Vista
* As a result of running in a different console, services cannot interact with the desktop. So essentially there is no direct UI support. You typically have to code a sibling UI application that does run as a normal program and uses some mechanism (named pipes for example) to communicate with the service.
* Typically only one instance of your service can be running at any given time.
* Processes are per user, services are per work station and hence often provide services for multiple users. | [This MSDN page](http://msdn.microsoft.com/en-us/library/y817hyb6(VS.80).aspx) leads to more documentation on creating them than you could shake a stick at. [This page](http://msdn.microsoft.com/en-us/library/d56de412(VS.80).aspx) is perhaps a better introduction to them in general.
The key difference between a process running as an app versus as a service is that the service can operate entirely outside the normal association with a user and session. Thus services can run such that they start before any user logs in and can continue running after users log off. Services are thus used to implement a great deal of the actual functionality of the operating system.
Services are also not tied to running as a 1:1 mapping with a process. Many services can exist within one process, normally through the use of svchost (take a look at these with process explorer for an indication of how this often works). This reduces the effort at startup as multiple processes are not required for relatively lightweight services.
Implementing a service in c# is pretty simple, this [page](http://www.codeproject.com/KB/system/WindowsService.aspx) indicates how in very easy to follow terms.
Note that in reality a service in windows is little more that the scaffolding in the registry under HKEY\_LOCAL\_MACHINE\System\CurrentControlSet\Services which defines those 'image paths' (in most cases simply executables and the parameters to use) which are considered services along with which user then run as, which other services they depend on and whether they start at start up/post start up or as required. | What is the difference between a windows service and a regular application? | [
"",
"c#",
"windows-services",
"comparison",
"windows",
""
] |
I have upgraded a set of databases from sql server 2000 to sql server 2008 and now large reads are blocking writes whereas this wasn't a problem in sql server 2000 (same databases and same applications & reports) Why? What setting in 2008 is different? Did 2000 default to read uncommitted transactions?
(update)
Adding with (nolock) to the report views in question fixes the problem in the short term - in the long run we'll have to make copies of the data for reporting either with snapshots or by hand. [sigh] I'd still like to know what about sql server 2008 makes this necessary.
(update 2) Since the views in question are only used for reports 'read uncommited' should be ok for now. | SQL Server 2000 did not use `READ UNCOMMITTED` by default, no.
It might have something to do with changes in optimizations in the execution plan. Some indexes are likely locked in a different order from what they were in SQL Server 2000. Or SQL Server 2008 is using an index that SQL Server 2000 was ignoring altogether for that particular query.
It's hard to say exactly what's going on without more information, but read up on lock types and check the execution plans for your two conflicting queries. Here's a nice [short article](http://mikedimmick.blogspot.com/2004/03/selectupdate-problem-or-why-updlock.html) that explains another example on why things can deadlock. | I'm actually surprised that you didn't run into problems in SQL Server 2000. It seems like every week we were fixing stored procedures that were locking tables because someone forgot nolocks. | sql server 2008 reads blocking writes | [
"",
"sql",
"sql-server-2008",
""
] |
I'm interested in creating a custom theme for a Drupal site I'm working on. I am new to Drupal, however I have a decent bit of experience in working with the underlying concepts that it seems are needed to build a theme (CSS, PHP, HTML).
So, my question is - where do I start? Is there a canonical guide to creating Drupal themes? Resources that I should be aware of (other than the [Theming Guide](http://drupal.org/theme-guide))? Gotchas that others have encountered, or just general words of wisdom from those who are more experienced? | The best way to do it is to start with a theme, and modify it bit by bit. That's how most of the people whom I know do it. You take the themes/garland directory and copy it to sites/all/themes/garland-modified, then you change a few things in it to reflect the new change (in principle you rename the .info file to the new directory location and you edit it to change garland to your new directory), then you go bit by bit and change things in the files to reflect your design.
This may seem tedious and a waste of time (why not just start from scratch?) but you have several advantages:
* you start with a working theme
* you start with a complete theme, wich everything you may want
* you don't risk of forgetting pieces which are required to have a working site
There are starter kits which are supposed to make things easier (see the zen theme for example) which you basically edit in a similar way I outlined above. But I found them a bit harder to understand...
Good luck with Drupal theming :) | Can I recommend you install the DEVEL module
<http://drupal.org/project/devel>
It can give you some really insightful clues how your page is being put together.
It also comes with a really useful feature called DRUAPL THEMER INFORMATION, which when activated lets you click on parts of your page, and tells you what bits of code did what.
My second tip is try and create your own node type templates, and then find out how the node data works.
For example in the theme folder create a new file called node-story.tpl.php
```
<?php
print "<textarea cols=100 rows=30>". print_r($node,true) ."</textarea>";
# or krumo($node); # if you have krumo installed
print "<h1>". $node->title ."</h1>";
print "<p>" . formdat_date($node->created,"custom", "d/m/Y) ."</p>" ;
?>
``` | Drupal Templating/Theming Resources or Advice? | [
"",
"php",
"drupal",
"web",
"themes",
""
] |
I Have this error: 'CLGDMFeed.Dal.DataManager' is inaccessible due to protection level.
And I have no Idea why i get this.
Tis is my class.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CLGDMFeed.Bol;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace CLGDMFeed.Dal
{
public static class DataManager
{
#region Methods
public static void SerializeFeed(string sFileName, Feed feed)
{
try
{
using (Stream stream = File.Open(sFileName, FileMode.Create))
{
BinaryFormatter binform = new BinaryFormatter();
binform.Serialize(stream, feed);
stream.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public static Feed DeSerializeFeed(string sFileName)
{
Feed feed;
try
{
using (Stream stream = File.Open(sFileName, FileMode.Open))
{
BinaryFormatter binform = new BinaryFormatter();
feed = (Feed)binform.Deserialize(stream);
stream.Close();
}
return feed;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public static void SerializeIListFeed(string sFileName, IList<Feed> list)
{
try
{
using (Stream stream = File.Open(sFileName, FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, list);
stream.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public static IList<Feed> DeSerializeIListFeed(string sFileName)
{
IList<Feed> list;
try
{
using (Stream stream = File.Open(sFileName, FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
list = (IList<Feed>)bf.Deserialize(stream);
stream.Close();
}
return list;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
#endregion
}
}
```
This is my form
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CLGDMFeed.Dal;
using CLGDMFeed.Bol;
namespace ViewerGDMFeed
{
public partial class Viewer : Form
{
//Lijst van object Deserializeren van een bestand zodat je ermee kan werken
IList<Feed> ListFeeds = DataManager.DeSerializeIListFeed("C:\\Documents and Settings\\sam\\Bureaublad\\Listfeeds.lfds");
public Viewer()
{
InitializeComponent();
//De namen van de feeds toevoegen aan je combobox
foreach (Feed feed in ListFeeds)
{
comboBox.Items.Add(feed.STitle);
}
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//Overlopen welke feed uit je lijst overeenkomt met de gekozen feed uit combox
foreach (Feed feed in ListFeeds)
{
if (comboBox.SelectedText == feed.STitle)
{
//De labels invullen met de juiste data
ViewerLabelTitle.Text = feed.STitle;
//...
}
}
}
}
}
```
Sorry for all the code
Does anyone kno how to solve tis problem?
Thanks
---
I have rebuild the classliberary and the error is gone.
But I have a new error: Metadata file 'C:\Documents and Settings\sam\Bureaublad\Herexamen programmeren\WindowsFormsApplication1\CLGDMFeed\bin\Debug\CLGDMFeed.dll' could not be found | seems like you have an invalid reference in your project | Found the problem! There was a method missing. GetObjectData. Stil don't get where the metadata file problem came from. thanx a lot for your answers.
Greetings | C# Error: 'Class' is inaccessible due to protection level | [
"",
"c#",
""
] |
I cant for the life of me remember what the word is. It's when you ???? several if/else/for/while/usings inside each other.
```
bool isTrue = true, isFalse = true, HasForgottenWord = true;
if( isTrue )
{
if( isFalse )
{
if( HasForgottenWord )
{
Console.WriteLine("Ask on StackOverflow.com - kthx bye");
}
}
}
``` | It's called nesting | Its called "nesting" them :) | What is it called when several conditional code blocks are inside each other? | [
"",
"c#",
""
] |
why are EventHandlers designed this way?
```
void uxSave_Click(object sender, EventArgs e)
```
why not this?
```
void uxSave_Click(Button sender, EventArgs e)
``` | Because in using the first way you can attach this click event to panel too. But if it is done second way if you have to controls events doing the same you need to define two events not attach one at two places. | Also, keep in mind that .NET did not have generics in version 1.0. Otherwise, a reasonable design might have defined the event handler to be:
```
public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e);
public event EventHandler<Control,ClickEventArgs> Click;
``` | Why are EventHandlers object parameter is just an object type? | [
"",
"c#",
"design-patterns",
""
] |
I'm using the ASP.NET binary for my FCKeditor, and needs to insert two editors on the same page. The uploaded images/browsing needs to go to two different directories, how do I do this from code-behind?
I know the path for uploaded files are set in the `config.ascx`-file with the `UserFilesPath` setting, but I can not find a way to override this value from my `aspx.cs` file.
Also, I found (conflicting) documentation stating that `Session["FCKeditor:UserFilesPath"]` could be set, but I dont like putting usercontrol-specific information in a global session variable. | first you need assign User Identity information into Session["UserInfo"]
then go to
[fckeditor root folder]/filemanager/connector/aspx/config.ascx
`string Userfolder = Session["UserInfo"].ToString();
// URL path to user files.
UserFilesPath = "~/Upload/" + Userfolder;` | Oh dear, after much struggle only thing I'm able to get is:
fckEditor1.Config
property. Try setting it for the editor you want to configure:
fckEditor1.Config["UserFilesPath"]="your path" | How do I change image upload path *dynamically* in FCKeditor | [
"",
"c#",
"upload",
"fckeditor",
""
] |
Can you recommend a ***single*** downloadable video (***one that you have actually watched*** and that you think is of high quality) introducing LINQ (not to be
confused with "LINQ to SQL") to a somewhat experienced VB.NET/C# developer?
It could be a screen-cast showing real code.
"Downloadable" includes YouTube and ShowMeDo (Flash video)
as there are ways to do this. A streaming-only video is not
acceptable. | Anders Hejlsberg gave a couple great introductory talks about LINQ at the Lang.NET Symposium in [2006](http://download.microsoft.com/download/9/4/1/94138e2a-d9dc-435a-9240-bcd985bf5bd7/AndersH-LINQ_0001.wmv) and [2008](http://download.microsoft.com/download/c/e/5/ce5434ca-4f54-42b1-81ea-7f5a72f3b1dd/1-01%20-%20CSharp3%20-%20Anders%20Hejlsberg.wmv). | Check out [LINQ Videos](http://www.asp.net/linq/videos) (www.asp.net). | .NET: recommended video tutorial for LINQ? | [
"",
"c#",
".net",
"vb.net",
"linq",
""
] |
I am trying this:
```
function add_things() {
var first = '2';
var second = '4';
alert(first + second);
}
```
But it gives me 24 instead of 6, what am I doing wrong? | You're concatenating two strings with the + operator. Try either:
```
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
```
or
```
function add_things() {
var first = '2';
var second = '4';
alert(parseInt(first, 10) + parseInt(second, 10));
}
```
or
```
function add_things() {
var first = '2';
var second = '4';
alert(Number(first) + Number(second));
}
```
**Note:** the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).
Also, as pointed out, octal is evil. `parseInt('010')` will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea. | Try this:
```
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
```
Note that I've removed the single quotes; `first` and `second` are now integers. In your original, they are strings (text). | why do I get 24 when adding 2 + 4 in javascript | [
"",
"javascript",
""
] |
I'm writing an app with ASP.NET MVC where, for various reasons, the navigation is handled through HTML input buttons. What are the Best practices on how to handle this situation?
1. Set up a Form on the buttons where information needs to be POSTed and just use JavaScript to redirect on the buttons where information doesn't need to be retained
2. Have all buttons handled through forms, to the point where a mini-form handles navigation on the buttons where the information doesn't need to be retained
```
<% using (Html.BeginForm())
{ %>
<input type="hidden" name="controller" value="1" />
<input type="hidden" name="action" value="Location" />
<input id="BackButton" type="submit" value="Go Back" />
<% } %>
```
3. Something I haven't thought of here | 1. Javascript is probably your best bet.
Using a mini form seems really heavy handed. You are basically looking to use a button as a link (I'd look seriously at why you are breaking that very basic web convention: buttons post/modify and links navigate) so the more basic you can make it the better. | [Here](http://particletree.com/features/rediscovering-the-button-element/) you can find a pretty good article on how to style an anchor tag like a button | Proper way to handle maneuvering through pages using buttons in ASP.NET MVC? | [
"",
"c#",
"asp.net-mvc",
"navigation",
""
] |
I've been using a linux machine for less than two weeks, so I am extremely new to Linux.
I'd also like to install the Java Developers Kit. How should this be done? Is there an `apt-get` command, or should I just click on the download button at Sun's website?
I'm sure there is more than one way to do this, and it probably doesn't matter much, but I was impressed with how smoothly `apt-get install` worked when installing PHP and MySQL, so if there is a *right* way to do this, I'd like to know.
I'm using Ubuntu version 9.04 | The Oracle JDK is no longer included in the Ubuntu repos. According to <https://stackoverflow.com/a/15543636/192221> , the following ppa can be used:
```
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java7-installer
```
If you have OpenJDK installed already, you might need to use
```
update-alternatives --config java
```
to use the Oracle Java by default. | Yes, definitely it's the suggested way to install JDK on your Linux system (if available).
On Ubuntu:
```
sudo apt-get install sun-java6-jdk
``` | Can `apt-get install` be used for JDK? | [
"",
"java",
"linux",
"ubuntu",
"installation",
"debian",
""
] |
I have some strange problem with PIL not resizing the image.
```
from PIL import Image
img = Image.open('foo.jpg')
width, height = img.size
ratio = floor(height / width)
newheight = ratio * 150
img.resize((150, newheight), Image.ANTIALIAS)
img.save('mugshotv2.jpg', format='JPEG')
```
This code runs without any errors and produces me image named `mugshotv2.jpg` in correct folder, but it does not resize it. It does something to it, because the size of the picture drops from 120 kb to 20 kb, but the dimensions remain the same.
Perhaps you can also suggest way to crop images into squares with less code. I kinda thought that `Image.thumbnail` does it, but what it did was that it scaled my image to 150 px by its width, leaving height 100px. | `resize()` returns a resized copy of an image. It doesn't modify the original. The correct way to use it is:
```
from PIL import Image
#...
img = img.resize((150, newheight), Image.ANTIALIAS)
```
[source](http://effbot.org/imagingbook/image.htm)
I think what you are looking for is the ImageOps.fit function. From PIL [docs](http://effbot.org/imagingbook/imageops.htm):
> ImageOps.fit(image, size, method, bleed, centering) => image
>
> Returns a sized and cropped version of
> the image, cropped to the requested
> aspect ratio and size. The size
> argument is the requested output size
> in pixels, given as a (width, height)
> tuple. | **[Update]**
ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.image.resize((100,100),Image.ANTIALIAS) | PIL Image.resize() not resizing the picture | [
"",
"python",
"resize",
"python-imaging-library",
""
] |
I'm trying to do a very basic date-difference calculation with javascript, but am getting mixed behavior from setInterval().
This updates constantly:
```
var init = setInterval(function(){
document.getElementById("txt").innerHTML = new Date();
}, 1000);
```
But this only updates once:
```
var init = setInterval(function(){
var today = new Date();
var started = new Date(); started.setYear(1983);
var difference = today - started;
document.getElementById("txt").innerHTML = difference;
}, 1000);
```
I don't get it. If I can show the date every second, why can't I show the difference in dates every second? | You're resetting `today` each time the function is called, so while the time changes, the difference between "today" and "today, 1983" is always the same.
Moving the assignment of `today` out of the interval, so it's only set once, worked for me. I see the number changing every second.
```
$(function () {
today = new Date();
var x = setInterval(function(){
started = new Date(); started.setYear(1983);
difference = today - started;
document.getElementById("txt").innerHTML = difference;
}, 1000);
});
``` | They both are executing once every 1000ms (1 per sec); however the second results in the same value every time, 820540800000. I assume you also realize that you can avoid polluting the global name space by judicious use of "var". | Strange behavior from setInterval() | [
"",
"javascript",
"datetime",
"setinterval",
""
] |
I am trying to make simple custom tags to allow custom templates on my app. But I can't figure out how to parse and replace the tags.
(example)
```
<div class="blog">
<module display="posts" limit="10" show="excerpt" />
</div>
<div class="sidebar">
<module display="users" limit="5" />
<module display="comment" limit="10" />
</div>
```
for each found module tag, I want to run the module creation function with the parameters (listed in the tag as attributes). And replace the module tag, with an actual HTML chunk that gets returned from the function. | You can use regular expressions to match your custom tags.
```
$html // Your html
preg_match_all('/<module\s*([^>]*)\s*\/?>/', $html, $customTags, PREG_SET_ORDER);
foreach ($customTags as $customTag) {
$originalTag=$customTag[0];
$rawAttributes=$customTag[1];
preg_match_all('/([^=\s]+)="([^"]+)"/', $rawAttributes, $attributes, PREG_SET_ORDER);
$formatedAttributes=array();
foreach ($attributes as $attribute) {
$name=$attribute[1];
$value=$attribute[2];
$formatedAttributes[$name]=$value;
}
$html=str_replace($originalTag, yourFunction($formatedAttributes), $html);
}
```
*If you would like to take a XML aproach, contact me and I'll show you how to do that.* | <https://www.php.net/manual/en/function.preg-replace-callback.php>
My partner has done work with tag parsing... depending on the complexity you wish to achieve, you may like to use regex. Use regex to find tags, and then you can split the strings up further with string manipulation functions of your own preference. The callback feature on preg\_replace\_callback will let you replace the tag with whatever html data you want it to represent. Cheers!
edit:
( < module +?([^=]+?="[^"]\*?" *?)*? *?/>)
This should match module functions... remove the space between the < and module (SO is parsing it wrong). In your custom function, match the individual parameters contained within the tag, using a regex like:
([^=]+?="[^"]*?") | Parsing Custom Tags with PHP | [
"",
"php",
"xml",
"parsing",
""
] |
Are there any reasons to use XML over properties files for Log4J configuration? | There's an interesting discussion on the [merits of both in this blog](http://www.laliluna.de/log4j-tutorial.html). The section below is a quote from that blog:
> Properties can be defined by a properties file or by an XML file. Log4j looks for a file named log4j.xml and then for a file named log4j.properties. *Both must be placed in the src folder*.
>
> The property file is less verbose than an XML file. The XML requires the log4j.dtd to be placed in the source folder as well. The XML requires a dom4j.jar which might not be included in older Java versions.
>
> The properties file does not support some advanced configuration options like Filters, custom ErrorHandlers and a special type of appenders, i.e. AsyncAppender. ErrorHandlers defines how errors in log4j itself are handled, for example badly configured appenders. Filters are more interesting. From the available filters, I think that the level range filter is really missing for property files.
>
> This filter allows to define that a[n] appender should receive log messages from Level INFO to WARN. This allows to split log messages across different logfiles. One for DEBUGGING messages, another for warnings, ...
>
> The property appender only supports a minimum level. If you set it do INFO, you will receive WARN, ERROR and FATAL messages as well.
---
To address the comments on my original answer: The italics are my emphasis. For the purposes of the tutorial the author has chosen to gloss over, or unintentionally omitted that the properties or xml need only be on the classpath rather than needing to be in the src folder. A simple way to add them to the classpath is to add them to the src folder, so for the purpose of the tutorial that was obviously deemed sufficient.
None of this is directly relevant to the question asked or the intention of the answer, which is to discuss the merits or otherwise of using xml files to configure log4j. I consider that the rest of the quote is relevant and useful to those looking to make an informed choice. | log4j is gradually moving to XML so properties is the legacy format.
Some new features can only be configured in XML. I was forced to switch to XMl because I need to use TimeBasedRollingPolicy.
However, XML is so verbose. I still use properties whenever I can. | Why chose XML over properties files for Log4J configuration? | [
"",
"java",
"xml",
"logging",
"log4j",
""
] |
So I'm using an SDK for a hardware random number generator which provides a dll called PsyREG.dll for interacting with it, as well as some c# source for using the methods from the dll.
It has worked in the past, but somehow it has stopped working. My hands are a bit tied as I don't actually have access to the device in question at the moment, so I can't try a lot of things...
However, here's the weird thing. The dll is there, the same place it's always been. Ahd in fact `File.Exists("PsyREG.dll")` returns `true`, and I've double checked and that's the exact same way the provided c# source imports it, e.g. `[DllImport("PsyREG.dll")]`.
Any ideas? | Probably this DLL has some dependencies that aren't registered or aren't in the same folder as your application. | Open DLL on the problematic system in <http://www.dependencywalker.com/> | DllNotFoundException, but DLL is there | [
"",
"c#",
"dllnotfoundexception",
""
] |
I am using GWT and Google App Engine. I have array of records and I want to update them every 30 mins.
In the *ServiceImpl* I have the fallowing code :
```
new Timer().schedule(new TimerTask(){
@Override
public void run() {
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
result = updateFeeds();
}
}, 30000,Long.MAX_VALUE);
```
When I run the application and when I get :
```
com.google.gwt.user.server.rpc.UnexpectedException:
Service method 'public abstract java.util.List org.joke.planet.client.FeedService.loadFeeds()' threw an unexpected exception:
java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)
```
at the first line or pasted code.
**My Question is HOW I can make a background worker that works in GWT+AppEngine Service ?** | You can't use java.util.Timer because it creates an ordinary thread, which is not allowed on AppEngine. However, you can use the AppEngine Modules API's Background thread facility, as documented here:
<https://developers.google.com/appengine/docs/java/modules/#Java_Background_threads>
Note that you can only use background threads on manually scaled instances. In this example, a background thread prints out a message every 30 seconds, forever:
```
Thread thread = ThreadManager.createBackgroundThread(new Runnable() {
public void run() {
try {
while (true) {
System.err.println("Doing something!");
Thread.sleep(30_000);
}
} catch (InterruptedException ex) {
}
}
});
thread.start();
``` | you cannot - a background worker implies a thread, and thread creation in gae does not work.
The answer to your task is not to create a thread or background worker, but to use this <http://code.google.com/appengine/docs/java/config/cron.html> | GWT, Google App Engine, TimerTask or Thread in ServiceImpl throw exception | [
"",
"java",
"google-app-engine",
"gwt",
"multithreading",
""
] |
In my project I have a factory method that loads an object that implements an interface. You pass in the class you desire and receive an instantiation of it, like so.
```
public class Factory {
public static <E extends SomeInterface> E load( Class<E> clss ) throws Exception {
return clss.newInstance();
}
}
```
You could invoke it like this:
```
MyObject obj = Factory.load( MyObject.class );
```
This code works just fine in Eclipse 3.4 with Java 6u13, however today I received a new laptop and installed Eclipse 3.5 and java 6u15 and now I am getting type mismatches everywhere.
```
MyObject obj = Factory.load( MyObject.class );
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type mismatch: cannot convert from SomeInterface to MyObject
```
Putting a cast before Factory on that line makes it go away and all runs well, but it makes the line a bit less clean, and I didn't need it before, so what gives? | Is that all the code required to get this bug? I've seen something very similar in some code I've been looking at today. There was an additional parameter being passed into the equivalent of your Factory method which had a generic type as well. This was missing it's generic definition and I think was to blame for confusing the compiler.
ie, if your factory method looked something like
```
public class Factory {
public static <E extends SomeInterface> E load( Class<E> class, Key key ) {
// return an instance of E
}
}
```
Where there is some Key class defined something like this
```
public class Key<Datatype> {
....
}
```
Giving something like this to invoke the method, note no generics on the declaration of key
```
Key key = new Key()
MyObject obj = Factory.load( MyObject.class, key );
```
Hope that helps, | Did you recently add a type parameter to your factory class? There's a pitfall with generic methods on raw types:
```
public class FooFactory<UnrelatedArg> {
public <E> E load(Class<E> c) { ... }
}
FooFactory<?> f; f.load(String.class); // returns String
FooFactory f; f.load(String.class); // returns Object
``` | Why has my generic method stopped working? | [
"",
"java",
"eclipse",
"generics",
""
] |
So I've got this database that helps organize information for academic conferences, but we need to know sometimes whether an item is "incomplete" - the rules behind what could make something incomplete are a bit complex, so I built them into a scalar function that just returns true if the item is complete and 0 otherwise.
The problem I'm running into is that when I call the function on a big table of data, it'll take about 1 minute to return the results. This is causing time-outs on the web site.
I don't think there's much I can do about the function itself. But I was wondering if anybody knows any techniques generally for these kinds of situations? What do you do when you have a big function like that that just has to be run sometimes on everything? Could I actually store the results of the function and then have it refreshed every now and then? Is there a good and efficient way to have it stored, but refresh it if the record is updated? I thought I could do that as a trigger or something, but if somebody ever runs a big update, it'll take forever.
Thanks,
Mike | If your function is that inefficient, you'll have to deal with either out of date data, or slow results.
It sounds like you care more about performance, so like @cmsjr said, add the data to the table.
Also, create a cron job to refresh the results periodically. Perhaps add an `updated` column to your database table, and then the cron job only has to re-process those rows.
One more thing, how complex is the function? Could you reduce the run-time of the function by pulling it out of SQL, perhaps writing it a layer above the database layer? | If the function is deterministic you could add it as a computed column, and then index on it, which might improve your performance.
[MSDN](http://msdn.microsoft.com/en-us/library/ms189292%28SQL.90%29.aspx) documentation. | SQL Efficiency with Function | [
"",
"sql",
"t-sql",
"function",
"performance",
""
] |
Is it better to cast the iterator condition right operand from `size_t` to `int`, or iterate potentially past the maximum value of `int`? Is the answer implementation specific?
```
int a;
for (size_t i = 0; i < vect.size(); i++)
{
if (some_func((int)i))
{
a = (int)i;
}
}
int a;
for (int i = 0; i < (int)vect.size(); i++)
{
if (some_func(i))
{
a = i;
}
}
``` | I almost always use the first variation, because I find that about 80% of the time, I discover that `some_func` should probably also take a size\_t.
If in fact `some_func` takes a signed int, you need to be aware of what happens when vect gets bigger than `INT_MAX`. If the solution isn't obvious in your situation (it usually isn't), you can at least replace `some_func((int)i)` with `some_func(numeric_cast<int>(i))` (see Boost.org for one implementation of numeric\_cast). This has the virtue of throwing an exception when vect grows bigger than you've planned on, rather than silently wrapping around to negative values. | I'd just leave it as a `size_t`, since there's not a good reason not to do so. What do you mean by "or iterate potentially up to the maximum value of type\_t"? You're only iterating up to the value of `vect.size()`. | Cast from size_t to int, or iterate with size_t? | [
"",
"c++",
""
] |
I am trying to figure out the best practices when loggin exceptions.
So far, I am logging every time I catch an exception. But when a lower lever class catches an exception (say, from the database layer), and wraps it in our own application exception - should I also log the original exception there, or should I just let the upper lever class log all the details?
And what about locations where my lower level class decides to throw an exception because of bad input parameters? Should it log the exception there also, or, once again, just let the catching code log it? | Mainly you should avoid logging it in both a lower-level catch and a higher-level catch, as this bloats the log with redundant information (not to mention takes up additional IO resources to write to the log).
If you are looking for general best practice information on exception handling, [this link is handy](http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx). | You can get away with logging only once at the very top level of your app, as long as your logging code (a) logs the stack trace of an exception, and (b) logs the entire chain of inner exceptions as well.
The Microsoft Exception Handling Application Block takes care of both of those things for you. I guess other logging frameworks would do the same. | Who should log an error/exception | [
"",
"c#",
"logging",
"exception",
""
] |
I want to show a PREVIEW kind of thing for an post , so took details by JS
but problem comes when it comes to `<input type="file"` , it's not giving full path to the file
Ex:
if I do
```
$("#image").val();
```
it only give "Sunset.jpg" not C:\Documents and Settings\All Users....\Sunset.jpg
any idea how to get that detail value? | Although, as others have already pointed out, you cannot learn the full path to the file in JavaScript, perhaps a completely different approach to the problem might still work for you.
You could upload the photo automatically as soon as the visitor has picked it (the behavior you see in GMail, among other applications), so it's residing on your server even as the visitor continues interacting with your page. At that point, showing a preview is as simple as serving one yourself from your own (now server-side) copy of the image. | This if for security reasons, so you cannot read files from the users system using JavaScript.
If you happen find a workaround, there will probably be security patches released by browser vendors sooner rather than later. I know because in earlier versions if IE, it was possible to read the full path and hence display a preview, at least if the file was an image. I used that in a CMS UI, but of course that nifty feature was ruined by an IE service release :-/
In general the file upload control is somewhat of a "black box" for security reasons. You have only very limited access to scripting and styling it. This is so you can't snoop or upload files without the user knowing, or so you cannot trick the user into uploading files with a deceptive interface. | Html file upload preview by Javascript | [
"",
"javascript",
"jquery",
"html",
"file",
""
] |
Is there a library in .net that does multithreaded compression of a stream? I'm thinking of something like the built in `System.IO.GZipStream`, but using multiple threads to perform the work (and thereby utilizing all the cpu cores).
I know that, for example 7-zip compresses using multiple threads, but the C# SDK that they've released doesn't seem to do that. | I think your best bet is to split the data stream at equal intervals yourself, and launch threads to compress each part separately in parallel, if using non-parallelized algorithms. (After which a single thread concatenates them into a single stream (you can make a stream class that continues reading from the next stream when the current one ends)).
You may wish to take a look at [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/) which is somewhat better than the intrinsic compression streams in .NET.
EDIT: You will need a header to tell where each new stream begins, of course. :) | Found this library: <http://www.codeplex.com/sevenzipsharp>
Looks like it wraps the unmanaged 7z.dll which does support multithreading. Obviously not ideal having to wrap unmanaged code, but it looks like this is currently the only option that's out there. | Multithreaded compression in C# | [
"",
"c#",
"multithreading",
"compression",
""
] |
I have a bunch of high quality PNG files. I want to use PHP to convert them to JPG because of it's smaller file sizes while maintaining quality. I want to display the JPG files on the web.
Does PHP have functions/libraries to do this? Is the quality/compression any good? | Do this to convert safely a PNG to JPG with the transparency in white.
```
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
``` | Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.
To convert, you may use the following function:
```
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
```
This function uses the [`imagecreatefrompng()`](http://docs.php.net/imagecreatefrompng) and the [`imagejpeg()`](http://docs.php.net/imagejpeg) functions from the GD library. | Use PHP to convert PNG to JPG with compression? | [
"",
"php",
"png",
"jpeg",
""
] |
I'm writing a screen-scraper for Stack Overflow. The bit I'm writing now takes the HTML and puts all the information into a model object. I've run into a bit of bother while parsing the information from an answer.
The problem is the date format that StackOverflow uses to describe absolute times. [`DateTime.Parse`](http://msdn.microsoft.com/en-us/library/1k1skd40.aspx) doesn't work on them. I've tried fooling around with [`DateTime.ParseExact`](http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx) but I've had no success. Both throw a [`FormatException`](http://msdn.microsoft.com/en-us/library/system.formatexception.aspx)
Here's some background:
If you look at the source HTML for an answer, you get this:
```
<div id="answer-{id}" class="answer">
<!-- ... -->
answered <span title="2009-06-18 13:21:16Z UTC" class="relativetime">Jun 18 at 13:21</span>
<!-- ... -->
</div>
```
Notice that the absolute time is stored in the span's title attribute. I've used the [HTML Agility Pack](http://codeplex.com/htmlagilitypack) from CodePlex to access the elements, and have extracted the value of the attribute.
Now I'm wondering how to get the `"2009-06-18 13:21:16Z UTC"` into a .NET [`DateTime`](http://msdn.microsoft.com/en-us/library/system.datetime.aspx) object.
I'd like to be able to do this without Regexes, etc., but as the whole project is hackish and unstable, I don't really mind!
Finally, I can't use the data dump for these reasons:
1. I can't use BitTorrent. Ever.
2. If I could, the files are too big for my net connection.
3. It's a bit out of date.
4. It's not as fun! | `"Z"` and `"UTC"` in the same `DateTime` string seems redundant.
If you remove `"UTC"` from the string, `Parse` works:
```
System.DateTime.Parse("2009-06-18 13:21:16Z")
{18.06.2009 15:21:16}
Date: {18.06.2009 00:00:00}
Day: 18
DayOfWeek: Thursday
DayOfYear: 169
Hour: 15
Kind: Local
Millisecond: 0
Minute: 21
Month: 6
Second: 16
Ticks: 633809352760000000
TimeOfDay: {15:21:16}
Year: 2009
``` | Well, you'd never use regex for this, but I think that format is just "u" described here: <http://msdn.microsoft.com/en-us/library/az4se3k1.aspx>
So ParseExact should accept that (with some minor work). | Parsing non-standard date string from Stack Overflow into a .NET DateTime | [
"",
"c#",
".net",
"datetime",
"screen-scraping",
""
] |
I am really new to online web application. I am using php, I got this code:
```
if(isset($_GET['return']) && !empty($_GET['return'])){
return = $_GET['return'];
header("Location: ./index.php?" . $return);
} else {
header("Location: ./index.php");
```
}
the `$return` variable is URL variable which can be easily changed by hacker.
E.g i get the `$return` variable from this : `www.web.com/verify.php?return=profile.php`
Is there anything I should take care? Should I use htmlentities in this line:
```
header("Location: ./index.php?" . htmlentities($return));
```
Is it vulnerable to attack by hacker?
What should i do to prevent hacking? | Apart from that typo on line 2 (should be $return = $\_GET['return'];) you should do [$return = urlencode($return)](http://fr3.php.net/manual/en/function.urlencode.php) to make sure that $return is a valid QueryString as it's passed as parameter to index.php.
index.php should then verify that return is a valid URL that the user has access to. I do not know how your index.php works, but if it simply displays a page then you could end up with someting like index.php?/etc/passwd or similar, which could indeed be a security problem.
**Edit:** What security hole do you get? There are two possible problems that I could see, depending how index.php uses the return value:
* If index.php redirects the user to the target page, then I could use your site as a relay to redirect the user to a site I control. This could be either used for phishing (I make a site that looks exactly like yours and asks the user for username/password) or simply for advertising.
+ For example, <http://yoursite/index.php?return?http%3A%2F%2Fwww.example.com> looks like the user accesses YourSite, but then gets redirected to www.example.com. As I can encode any character using the %xx notation, this may not even be obvious to the user.
* If index.php displays the file from the return-parameter, I could try to pass in the name of some system file like /etc/passwd and get a list of all users. Or I could pass something like ../config.php and get your database connection
+ I don't think that's the case here, but this is such a common security hole I'd still like to point it out.
As said, you want to make sure that the URL passed in through the querystring is valid. Some ways to do that could be:
* $newurl = "<http://yoursite/>" . $return;
+ this could ensure that you are always only on your domain and never redirect to any other domain
* $valid = [file\_exists](http://fr.php.net/manual/en/function.file-exists.php)($return)
+ This works if $return is always a page that exists on the hard drive. By checking that return indeed points to a valid file you can filter out bogus entries
+ If return would accept querystrings (i.e. return=profile.php?step=2) then you would need to parse out the "profile.php" path
* Have a list of valid values for $return and compare against it
+ this is usually impractical, unless you really designed your application so that index.php can only return t a given set of pages
There are many ways to skin this cat, but generally you want to somehow validate that $return points to a valid target. What those valid targets are depends on your specification. | If you're running an older version of both PHP 4 or 5, then I think you will be vulnerable to header injection - someone can set return to a URL, followed by a line return, followed by any other headers they want to make your server send.
You could avoid this by sanitising the string first. It might be enough to strip line returns but it would be better to have an allowed list of characters - this might be impractical.
> **4.4.2** and **5.1.2**: This function now prevents more than one header to be
> sent at once as a protection against
> header injection attacks.
<http://php.net/manual/en/function.header.php> | Is this code vulnerable to hacker attack? | [
"",
"php",
"security",
"url",
"variables",
""
] |
```
$rex = '/^[^<,"@?=>|;#]$/i';
```
I'm having trouble with this regular expression. The idea is that the input fields are checked for certain characters and if present, throw an error.
This regex is throwing errors for every string longer than 1 character. Can anyone tell me what I'm doing wrong?
EDIT: People are saying they don't see what I want to do with this regex. What I want to do is refuse the input if one of the following characters is part of the entered string:
< > , " @ ? = | ; #
EDIT2: JG's "valid" regex does the trick. | You have the `$` after your expression and the `^` in the beginning, which means you are accepting **exactly** one character.
**EDIT** (based on the comments):
You can try to see if your input fields **only** have **valid** characters, by matching it against this (if it matches, it means there are no invalid characters):
```
$rex = '/^[^<,"@$?=>|;#]+$/i'
```
You can also do the reverse, that is, test if your input fields have **any invalid** characters, using the regex provided by chaos:
```
$rex = '/[<,"@$?=>|;#]/';
```
This way, if the regex matches, then it means you have invalid characters. | What you probably actually need is:
```
$rex = '/[<,"@$?=>|;#]/';
```
Then your error case is when this regex matches, not when it doesn't.
This is equivalent to doing what you're currently doing with this small change to your regex:
```
$rex = '/^[^<,"@?=>|;#]*$/i';
```
This is kind of nonsensically overcomplex, though. Like trying to find out whether there's an elephant in the room by counting how many things in the room aren't elephants, then seeing if that number is the same as the number of things in the room. (And the `/i` modifier is not, at any time, accomplishing anything.) | Regex allows only 1 character | [
"",
"php",
"regex",
""
] |
Everyone here should know the 'or' statemens, usually glued to an die() command:
```
$foo = bar() or die('Error: bar function return false.');
```
The most of the times we see something like:
```
mysql_query('SELECT ...') or die('Error in during the query');
```
However, i cant understand how exactly that 'or' statement works.
I would like to throw a new exception instead of die(), but:
```
try{
$foo = bar() or throw new Exception('We have a problem here');
```
Doesnt work, and neither
```
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
```
The only way i found to do that is this horrible thought:
```
function ThrowMe($mess, $code){
throw new Exception($mess, $code);
}
try{
$foo = bar() or ThrowMe('We have a problem in here', 666);
}catch(Exception $e){
echo $e->getMessage();
}
```
But there is a way to throw a new exception directly after the 'or' statement?
Or this kind of structure is mandatory (i dont liek the ThrowMe function at all):
```
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
```
**Edit**: what i want is really to avoid the use of an if() check every potential dangerous operation i do, for example:
```
#The echo $e->getMessage(); is just an example, in real life this have no sense!
try{
$foo = bar();
if(!$foo){
throw new Exception('Problems with bar()');
}
$aa = bb($foo);
if(!$aa){
throw new Exception('Problems with bb()');
}
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i relly prefer to use something like:
try{
$foo = bar() or throw new Exception('Problems with bar()');
$aa = bb($foo) or throw new Exception('Problems with bb()');
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#Actually, the only way i figured out is:
try{
$foo = bar() or throw new ThrowMe('Problems with bar()', 1);
$aa = bb($foo) or throw new ThrowMe('Problems with bb()', 2);
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i'll love to thro the exception directly instead of trick it with ThrowMe function.
``` | `or` is just a [logical operator](https://www.php.net/manual/en/language.operators.logical.php), and it's analogous to `||`.
The common trick of
```
mysql_query() or die();
```
could just as well be written
```
mysql_query() || die();
```
What happens here is the "logical or" operator (whichever you choose) is trying to determine if either operand evaluates to TRUE. This means the operands must be expressions that can be cast as a boolean.
So, the reason
```
bar() or throw new Exception();
```
is illegal, is because
```
(boolean)throw new Exception();
```
is also illegal. In essence, the process of throwing an exception doesn't generate a return value for the operator to check.
But calling a function *does* generate a return value for the operator to check (no explicit return value will result int the function returning `NULL` which casts as `FALSE`) which is why it works for you when you wrap exception throwing in a function. | I've simply defined the function `toss` for this.
```
function toss(Exception $exception): void
{
throw $exception;
}
```
Because the file/line/stack information is captured when the exception is *constructed* (`new`) not thrown (`throw`) this doesn't interfere with the call stack.
So you can just do this.
```
something() or toss(new Exception('something failed'));
``` | PHP: 'or' statement on instruction fail: how to throw a new exception? | [
"",
"php",
"exception",
"logical-operators",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.