Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
What implementations of the [Prototype](http://en.wikipedia.org/wiki/Prototype_pattern) Pattern exist on the Java platform?
> A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
[Prototype based programming](http://en.wikipedia.org/wiki/Prototype-based_programming):
> Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes.
The implementation should be aware that some Java objects are mutable, and some are immutable (see [Mutable vs Immutable objects](https://stackoverflow.com/questions/214714/mutable-vs-immutable-objects)).
|
According to Josh Bloch and Doug Lea, [Cloneable is broken](http://www.artima.com/intv/bloch13.html). In that case, you can use a [copy constructor](http://www.javapractices.com/topic/TopicAction.do?Id=12).
|
Java defines the [Cloneable](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html) interface, described here at [JGuru](http://www.jguru.com/faq/view.jsp?EID=255004)
> Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to create a new instance of the object with the same values.
Warning: see [Cloneable is broken](http://www.artima.com/intv/bloch13.html)
|
Java implementations of the Prototype Pattern
|
[
"",
"java",
"oop",
"design-patterns",
"prototype-pattern",
""
] |
How can i map a date from a java object to a database with Hibernate? I try different approaches, but i am not happy with them. Why? Let me explain my issue. I have the following class [1] including the main method i invoke and with the following mapping [2]. The issue about this approach you can see, when you look at the console output.
> false
>
> false
>
> 1
>
> -1
>
> 1224754335648
>
> 1224754335000
>
> Thu Oct 23 11:32:15 CEST 2008
>
> Clock@67064
As you can see the the to dates are not exactly equal, although they should, so it is hard to compare them without goofing around with return value of `getTime`. I also tried java.sql.Date, Timestamp and date instead of timestamp in the mapping, but without success.
I wonder why the last three digits are zero and if this is a hibernate or a java issue or my own stupidity.
Thank you for reading.
[1]
```
public class Clock {
int id;
java.util.Date date;
public static void main(String[] args) {
HibernateUtil.init();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Clock clock = new Clock();
clock.date = new java.util.Date();
HibernateUtil.getSessionFactory().getCurrentSession().saveOrUpdate(clock);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
Clock fromDBClock = (Clock)HibernateUtil.getSessionFactory()
.getCurrentSession().get(Clock.class, 1);
System.out.println(clock.date.equals(fromDBClock.date));
System.out.println(fromDBClock.date.equals(clock.date));
System.out.println(clock.date.compareTo(fromDBClock.date));
System.out.println(fromDBClock.date.compareTo(clock.date));
System.out.println(clock.date.getTime());
System.out.println(fromDBClock.date.getTime());
System.out.println(clock.date.toString());
System.out.println(fromDBClock.toString());
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
HibernateUtil.end();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
}
```
[2]
```
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Clock" table="CLOCK">
<id name="id" column="CLOCK_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp"/>
</class>
</hibernate-mapping>
```
|
MySql DateTime precision is only to the second. Java Date precision is to the millisecond.
That is why the last three digits are zeros after it has been put in the database.
Do this to your original Date:
date = date.setTime((date.getTime() / 1000) \* 1000);
This will set it to the last exact second, and all your comparisons will then match.
(BTW,
System.out.println(fromDBClock.toString());
should be
System.out.println(fromDBClock.date.toString());
|
SQL Server stores datetime with a precision of 3 milliseconds which can definitely cause the problem you're seeing. One fallout of this is that 23:59:59.999 in Java ends up being the next day in SQL Server. I've never had a problem with Oracle, Informix, or MySQL, but other databases may have less precision also. You can work around it by using Hibernate custom types. You have to round to something less precise than the underlying database precision when you write out the date values. Search for UserType in the Hibernate documentation, you'll be changing the nullSafeSet method to do the rounding.
|
Comparing hibernate-mapped dates?
|
[
"",
"java",
"hibernate",
"date",
""
] |
Is it possible to somehow mark a `System.Array` as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:
```
public class Immy
{
public string[] { get; private set; }
}
```
I thought the `readonly` keyword might do the trick, but no such luck.
|
[`ReadOnlyCollection<T>`](http://msdn.microsoft.com/en-us/library/ms132474) is probably what you are looking for. It doesn't have an `Add()` method.
|
The [Framework Design Guidelines](https://rads.stackoverflow.com/amzn/click/com/0321246756) suggest returning a copy of the Array. That way, consumers can't change items from the array.
```
// bad code
// could still do Path.InvalidPathChars[0] = 'A';
public sealed class Path {
public static readonly char[] InvalidPathChars =
{ '\"', '<', '>', '|' };
}
```
these are better:
```
public static ReadOnlyCollection<char> GetInvalidPathChars(){
return Array.AsReadOnly(InvalidPathChars);
}
public static char[] GetInvalidPathChars(){
return (char[])InvalidPathChars.Clone();
}
```
The examples are straight from the book.
|
Are immutable arrays possible in .NET?
|
[
"",
"c#",
".net",
"arrays",
"immutability",
""
] |
I find print\_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?
|
Note @tchrist recommends [Data::Dump](http://search.cpan.org/~gaas/Data-Dump-1.21/lib/Data/Dump.pm) over [Data::Dumper](http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm). I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.
[Data::Dumper](http://search.cpan.org/~jhi/perl-5.8.0/ext/Data/Dumper/Dumper.pm) :
A snippet of the examples shown in the above link.
```
use Data::Dumper;
package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
package Fuz; # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};
package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
{1 => 'a', 023 => 'b', 0x45 => 'c'},
\\"p\q\'r", $foo, $fuz];
########
# simple usage
########
$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar); # pretty print (no array indices)
$Data::Dumper::Terse = 1; # don't output names where feasible
$Data::Dumper::Indent = 0; # turn off all pretty print
print Dumper($boo), "\n";
$Data::Dumper::Indent = 1; # mild pretty print
print Dumper($boo);
$Data::Dumper::Indent = 3; # pretty print with array indices
print Dumper($boo);
$Data::Dumper::Useqq = 1; # print strings in double quotes
print Dumper($boo);
```
|
As usually with Perl, you might prefer alternative solutions to the venerable Data::Dumper:
* [Data::Dump::Streamer](http://search.cpan.org/dist/Data-Dump-Streamer/) has a terser output than Data::Dumper, and can also serialize some data better than Data::Dumper,
* [YAML](http://search.cpan.org/dist/YAML) (or [Yaml::Syck](http://search.cpan.org/dist/YAML-Syck/), or an other YAML module) generate the data in YAML, which is quite legible.
And of course with the debugger, you can display any variable with the 'x' command. I particularly like the form '`x 2 $complex_structure`' where 2 (or any number) tells the debugger to display only 2 levels of nested data.
|
What is Perl's equivalent to PHP's print_r()?
|
[
"",
"php",
"perl",
"debugging",
""
] |
In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem.
In Vista it instead returns the date that the picture is copied from the camera.
How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".
|
Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10 × as fast on my machine.
```
//we init this once so that if the function is repeatedly called
//it isn't stressing the garbage man
private static Regex r = new Regex(":");
//retrieves the datetime WITHOUT loading the whole image
public static DateTime GetDateTakenFromImage(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (Image myImage = Image.FromStream(fs, false, false))
{
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
}
```
And yes, the correct id is 36867, not 306.
The other Open Source projects below should take note of this. It is a *huge* performance hit when processing thousands of files.
|
I maintained a [simple open-source library](https://github.com/drewnoakes/metadata-extractor-dotnet) since 2002 for extracting metadata from image/video files.
```
// Read all metadata from the image
var directories = ImageMetadataReader.ReadMetadata(stream);
// Find the so-called Exif "SubIFD" (which may be null)
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
// Read the DateTime tag value
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTimeOriginal);
```
In my benchmarks, this code runs over 12 times faster than `Image.GetPropertyItem`, and around 17 times faster than the WPF `JpegBitmapDecoder`/`BitmapMetadata` API.
There's a tonne of extra information available from the library such as camera settings (F-stop, ISO, shutter speed, flash mode, focal length, ...), image properties (dimensions, pixel configurations) and other things such as GPS positions, keywords, copyright info, etc.
If you're only interested in the metadata, then using this library is very fast as it doesn't decode the image (i.e. bitmap). You can scan thousands of images in a few seconds if you have fast enough storage.
`ImageMetadataReader` understands many files types (JPEG, PNG, GIF, BMP, TIFF, PCX, WebP, ICO, ...). If you *know* that you're dealing with JPEG, and you *only* want Exif data, then you can make the process even faster with the following:
```
var directories = JpegMetadataReader.ReadMetadata(stream, new[] { new ExifReader() });
```
The *metadata-extractor* library is available via [NuGet](https://www.nuget.org/packages/MetadataExtractor/) and the [code's on GitHub](https://github.com/drewnoakes/metadata-extractor-dotnet). Thanks to all the amazing contributors who have improved the library and submitted test images over the years.
|
How can I find out when a picture was actually taken in C# running on Vista?
|
[
"",
"c#",
""
] |
Right now, I have a SQL Query like this one:
```
SELECT X, Y FROM POINTS
```
It returns results like so:
```
X Y
----------
12 3
15 2
18 12
20 29
```
I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag):
```
XYLIST
----------
12,3,15,2,18,12,20,29
```
Is there a way to do this using just SQL?
|
```
DECLARE @XYList varchar(MAX)
SET @XYList = ''
SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','
FROM POINTS
-- Remove last comma
SELECT LEFT(@XYList, LEN(@XYList) - 1)
```
|
Thanks for the quick and helpful answers guys!
I just found another fast way to do this too:
```
SELECT STUFF(( SELECT ',' + X + ',' + Y
FROM Points
FOR
XML PATH('')
), 1, 1, '') AS XYList
```
Credit goes to this guy:
[Link](https://web.archive.org/web/20200217202303/http://geekswithblogs.net:80/mnf/archive/2007/10/02/t-sql-user-defined-function-to-concatenate-column-to-csv-string.aspx)
|
How can I combine multiple rows into a comma-delimited list in SQL Server 2005?
|
[
"",
"sql",
"sql-server",
"list",
"function",
"concatenation",
""
] |
I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?
|
In a debug compilation, [`Assert`](https://msdn.microsoft.com/en-us/library/kssw4w7z.aspx "MSDN Debug.Assert") takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
If you compile in Release, all [`Debug.Assert`](https://msdn.microsoft.com/en-us/library/kssw4w7z(v=vs.110).aspx#Remarks "MSDN Debug.Assert Remarks")'s are automatically left out.
|
From [Code Complete](https://web.archive.org/web/20161126131145/http://cc2e.com/)
> ## 8 Defensive Programming
>
> ### 8.2 Assertions
>
> An assertion is code that’s used during development—usually a routine
> or macro—that allows a program to check itself as it runs. When a
> assertion is true, that means everything is operating as expected.
> When it’s false, that means it has detected an unexpected error in the
> code. For example, if the system assumes that a customer-information
> file will never have more than 50,000 records, the program might
> contain an assertion that the number of records is less than or equal
> to 50,000. As long as the number of records is less than or equal to
> 50,000, the assertion will be silent. If it encounters more than
> 50,000 records, however, it will loudly “assert” that there is a
> error in the program.
>
> Assertions are especially useful in large, complicated programs and
> in high-reliability programs. They enable programmers to more quickly
> flush out mismatched interface assumptions, errors that creep in when the code is modified, and so on.
>
> An assertion usually takes two arguments: a boolean expression that
> describes the assumption that’s supposed to be true and a message to
> display if it isn’t.
>
> (…)
>
> Normally, you don’t want users to see assertion messages in
> production code; assertions are primarily for use during development
> and maintenance. Assertions are normally compiled into the code at
> development time and compiled out of the code for production. During
> development, assertions flush out contradictory assumptions,
> unexpected conditions, bad values passed to routines, and so on.
> During production, they are compiled out of the code so that the
> assertions don’t degrade system performance.
|
C# - What does the Assert() method do? Is it still useful?
|
[
"",
"c#",
"assert",
""
] |
What exactly does null do performance and storage (space) wise in MySQL?
For example:
TINYINT: 1 Byte
TINYINT w/NULL 1 byte + somehow stores NULL?
|
It depends on which storage engine you use.
In MyISAM format, each row header contains a bitfield with one bit for each column to encode NULL state. A column that is NULL still takes up space, so NULL's don't reduce storage. See <https://dev.mysql.com/doc/internals/en/myisam-introduction.html>
In InnoDB, each column has a "field start offset" in the row header, which is one or two bytes per column. The high bit in that field start offset is on if the column is NULL. In that case, the column doesn't need to be stored at all. So if you have a lot of NULL's your storage should be significantly reduced.
See <https://dev.mysql.com/doc/internals/en/innodb-field-contents.html>
**EDIT:**
The NULL bits are part of the row headers, you don't choose to add them.
The only way I can imagine NULLs improving performance is that in InnoDB, a page of data may fit more rows if the rows contain NULLs. So your InnoDB buffers may be more effective.
But I would be very surprised if this provides a significant performance advantage in practice. Worrying about the effect NULLs have on performance is in the realm of micro-optimization. You should focus your attention elsewhere, in areas that give greater bang for the buck. For example adding well-chosen indexes or increasing database cache allocation.
|
Bill's answer is good, but a little bit outdated. The use of one or two bytes for storing NULL applies **only** to InnoDB REDUNDANT row format. Since MySQL 5.0.3 InnoDB uses **COMPACT** row format which uses only one bit to store a NULL (of course one byte is the minimum), therefore:
Space Required for NULLs = **CEILING(N/8) bytes** where N is the number of NULL columns in a row.
* 0 NULLS = 0 bytes
* 1 - 8 NULLS = 1 byte
* 9 - 16 NULLS = 2 bytes
* 17 - 24 NULLS = 3 bytes
* etc...
According to the official MySQL site about COMPACT vs REDUNDANT:
> The compact row format decreases row storage space by about 20% at the cost of increasing CPU use for some operations. If your workload is a typical one that is limited by cache hit rates and disk speed, compact format is likely to be faster.
## Advantage of using NULLS over Empty Strings or Zeros:
* 1 NULL requires 1 byte
* 1 Empty String requires 1 byte (assuming VARCHAR)
* 1 Zero requires 4 bytes (assuming INT)
You start to see the savings here:
* 8 NULLs require 1 byte
* 8 Empty Strings require 8 bytes
* 8 Zeros require 32 bytes
On the other hand, I suggest using NULLs over empty strings or zeros, because they're more organized, portable, and require less space. To improve performance and save space, focus on using the proper data types, indexes, and queries instead of weird tricks.
More on:
<https://dev.mysql.com/doc/refman/5.7/en/innodb-physical-record.html>
|
NULL in MySQL (Performance & Storage)
|
[
"",
"sql",
"mysql",
"null",
""
] |
I've been trying for a while now to write a unit test for a UserViewControl in ASP.NET MVC. I'd like to get to code that looks something like this:
```
[TestMethod]
public void HaveControlToDisplayThings()
{
var listControl = new ControlUnderTest();
var viewData = new ViewDataDictionary<IList<string>>(this.repo.GetMeSomeData());
// Set up a ViewContext using Moq.
listControl.SetFakeViewContext(viewData);
listControl.ViewData = viewData;
listControl.RenderView(listControl.ViewContext);
// Never got this far, no idea if this will work :)
string s = listControl.ViewContext.HttpContext.Response.Output.ToString();
Assert.AreNotEqual(0, s.Length);
foreach (var item in this.repo.GetMeSomeData())
{
Assert.IsTrue(s.IndexOf(item) != -1);
}
}
```
Unfortunately, no matter what I try I get errors from deep inside RenderView. This is caused (as far as I can tell) by the static HttpContext.Current object being useless - I get `NullReferenceException`s from `System.Web.UI.Page.SetIntrinsics`.
I tried using Phil Haack's [HttpSimulator](http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx) which gave me a HttpContext object but I found I also needed to specify a fake `HttpBrowserCapabilities` object to get slightly further:
```
Subtext.TestLibrary.HttpSimulator simulator = new HttpSimulator();
simulator.SimulateRequest();
var browserMock = new Mock<HttpBrowserCapabilities>();
browserMock.Expect(b => b.PreferredRenderingMime).Returns("text/html");
browserMock.Expect(b => b.PreferredResponseEncoding).Returns("UTF-8");
browserMock.Expect(b => b.PreferredRequestEncoding).Returns("UTF-8");
HttpContext.Current.Request.Browser = browserMock.Object;
```
Now I get exceptions on property accesses on that object. I mocked as many as I could, but seemed to be getting nowhere fast.
Has anyone managed to make this work?
|
Unfortunately, the ASP.NET viewengine uses the VirtualPathProvider in the ASP.NET hosting environment. To make matters worse, I traced some of the other code using Reflector and found that there is other dependencies to some hardcode references to VirtualPath utilities.
I hope they fix this in the release so we can truly test our Views and how they are rendered.
|
One option would be to run unit tests inside the browser. I've had success with [Selenium](http://seleniumhq.org/) for such cases.
|
How can I unit test an MVC UserViewControl?
|
[
"",
"c#",
"asp.net-mvc",
"mocking",
""
] |
The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.
It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.
|
Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm.
See example for client (**untested code**):
---
```
using System.Net;
using System.Net.Sockets;
[STAThread]
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 8002));
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));
socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello"));
int availableBytes = socket.Available;
if (availableBytes > 0)
{
byte[] buffer = new byte[availableBytes];
socket.Receive(buffer, 0, availableBytes, SocketFlags.None);
// buffer has the information on how to connect to the server
}
}
```
|
I'd say the best way is to use Bonjour/Zeroconf/mDNS for C#; a lot of thought went into making it play nice with the network; IE it pings less frequently over time if possible, etc. There's [Mono.Zeroconf](http://mono-project.com/Mono%2eZeroconf), and I read there's an older .NET project in the [Apple SDK](http://developer.apple.com/networking/bonjour/download/) but I haven't found it.
So the easiest would be to install [Bonjour for Windows](http://developer.apple.com/networking/bonjour/download/), then get the [Windows Binaries for Mono.Zeroconf](http://download.banshee-project.org/mono-zeroconf/mono-zeroconf-0.8.0-binary.zip) try the example `MZClient.exe` drop the `Mono.Zeroconf.dll` and/or `Mono.Zeroconf.Providers.Bonjour.dll` into your project references and go.
Something like this:
```
var service = new Mono.Zeroconf.RegisterService {
Name = "Use Me for Stuff",
RegType = "_daap._tcp",
ReplyDomain = "local.",
Port = 0024200,
TxtRecord = new Mono.Zeroconf.TxtRecord {
{"I have no idea what's going on", "true"}}
};
service.Register();
var browser = new Mono.Zeroconf.ServiceBrowser();
browser.ServiceAdded +=
delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) {
Console.WriteLine("Found Service: {0}", args.Service.Name);
args.Service.Resolved +=
delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) {
var s = args.Service;
Console.WriteLine(
"Resolved Service: {0} - {1}:{2} ({3} TXT record entries)",
s.FullName, s.HostEntry.AddressList[0], s.Port, s.TxtRecord.Count);
};
args.Service.Resolve();
};
browser.Browse("_daap._tcp", "local");
```
|
What is the best way for a client app to find a server on a local network in C#?
|
[
"",
"c#",
"remoting",
"client-server",
"service-discovery",
""
] |
I saw this question asked about C# I would like an answer for PHP. I have some old code that has 4 pages of foreach loops and conditions which just makes it hard to read and follow. How would I make this more OO? I was thinking of using SPL Functions but don't fully understand whats involved yet.
|
This code can probably be cleaned up significantly, and pushed far in the direction of OO, without touching SPL.
SPL is only needed if you want to alter normal object behaviour in language constructs like foreach(), or in builtins like count(), or in array access funcitons (both operator [] and functions like key(), next() etc).
Cleanup suggestions:
* If the same action is performed several (more than 1 or 2) times in the code, break it out into a function. If this action is to be performed on all elements in a array, consider using [array\_walk](http://php.net/array_walk). If walking the array doesn't fit for some reason, use a loop :)
- If you have several instances of some semantically connected data more complex than a key:value pair, with associated operations, consider wrapping it in a class. But a formally documented assoc. array might suit you just as well. Depends on your style, and on the type of data. The important thing here is the structuring of methods working on th data, and the documentation. Doesn't really matter if you make it a class or not.
- After you have done the above steps, break the newly written functions and objects out into separate include files. I tend towards wrapping most everything in a class, so I mostly have one class pr. file. But some helper classes share a file with the main class, etc. You'll get a feel for it.
|
If I were you, I'd start by writing test code.
If you can build up a set of testcases that fully describe the functionality you're refactoring, you can go ahead and rewrite your code safe in the knowledge that it will still work.
[PHPUnit](http://phpunit.sourceforge.net) might be a good place to start with this.
|
Remove repetitive, hard coded loops and conditions in PHP
|
[
"",
"php",
"spl",
""
] |
I have a table that looks like that:

The rows are sorted by CLNDR\_DATE DESC.
I need to find a CLNDR\_DATE that corresponds to the highlighted row, in other words:
Find the topmost group of rows WHERE EFFECTIVE\_DATE IS NOT NULL,
and return the CLNR\_DATE of a last row of that group.
Normally I would open a cursor and cycle from top to bottom until I find a NULL in EFFECTIVE\_DATE. Then I would know that the date I am looking for is CLNDR\_DATE, obtained at the previous step.
However, I wonder if the same can be achieved with a single SQL?
|
Warning: Not a DBA by any means. ;)
But, a quick, untested stab at it:
```
SELECT min(CLNDR_DATE) FROM [TABLE]
WHERE (EFFECTIVE_DATE IS NOT NULL)
AND (CLNDR_DATE > (
SELECT max(CLNDR_DATE) FROM [TABLE] WHERE EFFECTIVE_DATE IS NULL
))
```
Assuming you want the **first** CLNDR\_DATE **with** EFFECTIVE\_DATE after the **last without**.
If you want the **first with** after the **first without**, change the subquery to use min() instead of max().
|
Using Oracle's analytic function (untested)
```
select *
from
(
select
clndr_date,
effective_date,
lag(clndr_date, 1, null) over (order by clndr_date desc) prev_clndr_date
from table
)
where effective_date is null
```
The `lag(clndr_date, 1, null) over (order by clndr_date desc)` returns the previous clndr\_date, or use null if this is the first row.
(edit: fixed order)
|
Do this with a single SQL
|
[
"",
"sql",
"oracle",
""
] |
How do I limit `os.walk` to only return files in the directory I provide it?
```
def _dir_list(self, dir_name, whitelist):
outputList = []
for root, dirs, files in os.walk(dir_name):
for f in files:
if os.path.splitext(f)[1] in whitelist:
outputList.append(os.path.join(root, f))
else:
self._email_to_("ignore")
return outputList
```
|
Use the `walklevel` function.
```
import os
def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs, files
num_sep_this = root.count(os.path.sep)
if num_sep + level <= num_sep_this:
del dirs[:]
```
It works just like `os.walk`, but you can pass it a `level` parameter that indicates how deep the recursion will go.
|
Don't use os.walk.
Example:
```
import os
root = "C:\\"
for item in os.listdir(root):
if os.path.isfile(os.path.join(root, item)):
print item
```
|
os.walk without digging into directories below
|
[
"",
"python",
"file",
"os.walk",
""
] |
I would like to do remote deployment from my build machine onto a server. The remoting can be done via ssh commands from a script, but I would rather use phing and a deploy.xml file that would do the automation.
What alternatives do I have to do ssh (and also scp) tasks from within a phing build file?
|
If you really need phing, then afaik there's only exec. If you are open for other tools, have a look at [capistrano](http://www.capify.org/) and my answer in "[Setting up a PHP web project, the infrastructure.](https://stackoverflow.com/questions/220638/setting-up-a-php-web-project-the-infrastructure#225524)".
|
[SCPTask](https://www.phing.info/docs/guide/stable/ScpTask.html) in Phing:
> copies files to and from a remote host using scp. This task requires the **[PHP SSH2 extension](http://web.archive.org/web/20101219161808/http://pecl.php.net/package/ssh2)** to function...
|
Are there ssh and scp tasks available for phing?
|
[
"",
"php",
"deployment",
"phing",
""
] |
I am writing some JNI code in C that I wish to test using cunit. In order to call the JNI functions, I need to create a valid JNIEnv struct.
Does anyone know if there is a mocking framework for such a purpose, or who can give me some pointers on how to create a mock JNIEnv struct myself?
|
jni.h contains the complete structure for JNIEnv\_, including the "jump table" JNINativeInterface\_. You could create your own JNINativeInterface\_ (pointing to mock implementations) and instantiate a JNIEnv\_ from it.
Edit in response to comments: (I didn't look at the other SO question you referenced)
```
#include "jni.h"
#include <iostream>
jint JNICALL MockGetVersion(JNIEnv *)
{
return 23;
}
JNINativeInterface_ jnini = {
0, 0, 0, 0, //4 reserved pointers
MockGetVersion
};
// class Foo { public static native void bar(); }
void Java_Foo_bar(JNIEnv* jni, jclass)
{
std::cout << jni->GetVersion() << std::endl;
}
int main()
{
JNIEnv_ myjni = {&jnini};
Java_Foo_bar(&myjni, 0);
return 0;
}
```
|
Mocking JNI sounds like a world of pain to me. I think you are likely to be better off mocking the calls implemented in Java, and using Junit to test the functionality on the java side
|
How to create a JNIEnv mock in C/C++
|
[
"",
"c++",
"c",
"mocking",
"java-native-interface",
"cunit",
""
] |
Is it quicker to make one trip to the database and bring back 3000+ plus rows, then manipulate them in .net & LINQ or quicker to make 6 calls bringing back a couple of 100 rows at a time?
|
Is this for one user, or will many users be querying the data? The single database call will scale better under load.
|
It will entirely depend on the speed of the database, the network bandwidth and latency, the speed of the .NET machine, the actual queries etc.
In other words, we can't give you a truthful general answer. I know which sounds easier to code :)
Unfortunately this is the kind of thing which you can't easily test usefully without having an *exact* replica of the production environment - most test environments are somewhat different to the production environment, which could seriously change the results.
|
Which is fastest? Data retrieval
|
[
"",
"asp.net",
"sql",
"database",
"linq",
""
] |
I'm experimenting with generics and I'm trying to create structure similar to Dataset class.
I have following code
```
public struct Column<T>
{
T value;
T originalValue;
public bool HasChanges
{
get { return !value.Equals(originalValue); }
}
public void AcceptChanges()
{
originalValue = value;
}
}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
public bool HasChanges
{
get
{
return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges;
}
}
public void AcceptChanges()
{
id.AcceptChanges();
name.AcceptChanges();
someDate.AcceptChanges();
someInt.AcceptChanges();
}
}
```
Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring.
So first solution that cames to my mind was something like this:
```
public interface IColumn
{
bool HasChanges { get; }
void AcceptChanges();
}
public struct Column<T> : IColumn {...}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }}
public bool HasChanges
{
get
{
bool has = false;
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
has |= columns[i].HasChanges;
return has;
}
}
public void AcceptChanges()
{
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
columns[i].AcceptChanges(); //Here we are changing clone
}
}
```
As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me.
So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage.
**Edit:**
sfg thanks for suggestion about macros.
In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain.
Some usefull links:
[T4 Editor for VS](http://www.t4editor.net/ "T4 Editor for VS")
[Blog with links and tutorials about T4](http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ "Blog with links and tutorials about T4")
[Blog entry with example that uses EnvDTE to read project files](http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/ "Blog entry with example that uses EnvDTE to read project files")
|
As you asked for examples from functional languages; in lisp you could prevent the writing of all that code upon each addition of a column by using a macro to crank the code out for you. Sadly, I do not think that is possible in C#.
In terms of performance: the macro would be evaluated at compile time (thus slowing compilation a tiny amount), but would cause no slow-down at run-time as the run-time code would be the same as what you would write manually.
I think you might have to accept your original AcceptChanges() as you need to access the structs directly by their identifiers if you want to avoid writing to cloned versions.
In other words: you need a program to write the program for you, and I do not know how to do that in C# without going to extraordinary lengths or losing more in performance than you ever would by switching the structs to classes (e.g. reflection).
|
Honestly, it sounds like you really want these `Column`s to be classes, but don't want to pay the runtime cost associated with classes, so you're trying to make them be structs. I don't think you're going to find an elegant way to do what you want. Structs are supposed to be value types, and you want to make them behave like reference types.
You cannot efficiently store your Columns in an array of `IColumn`s, so no array approach is going to work well. The compiler has no way to know that the `IColumn` array will only hold structs, and indeed, it wouldn't help if it did, because there are still different types of structs you are trying to jam in there. Every time someone calls `AcceptChanges()` or `HasChanges()`, you're going to end up boxing and cloning your structs anyway, so I seriously doubt that making your `Column` a struct instead of a class is going to save you much memory.
However, you *could* probably store your `Column`s directly in an array and index them with an enum. E.g:
```
public class Record
{
public enum ColumnNames { ID = 0, Name, Date, Int, NumCols };
private IColumn [] columns;
public Record()
{
columns = new IColumn[ColumnNames.NumCols];
columns[ID] = ...
}
public bool HasChanges
{
get
{
bool has = false;
for (int i = 0; i < columns.Length; i++)
has |= columns[i].HasChanges;
return has;
}
}
public void AcceptChanges()
{
for (int i = 0; i < columns.Length; i++)
columns[i].AcceptChanges();
}
}
```
I don't have a C# compiler handy, so I can't check to see if that will work or not, but the basic idea should work, even if I didn't get all the details right. However, I'd just go ahead and make them classes. You're paying for it anyway.
|
class with valueTypes fields and boxing
|
[
"",
"c#",
"data-structures",
"t4",
""
] |
I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields.
Something like firefox live headers, but for the server side.
|
The middleware
```
from wsgiref.util import request_uri
import sys
def logging_middleware(application, stream=sys.stdout):
def _logger(environ, start_response):
stream.write('REQUEST\n')
stream.write('%s %s\n' %(
environ['REQUEST_METHOD'],
request_uri(environ),
))
for name, value in environ.items():
if name.startswith('HTTP_'):
stream.write(' %s: %s\n' %(
name[5:].title().replace('_', '-'),
value,
))
stream.flush()
def _start_response(code, headers):
stream.write('RESPONSE\n')
stream.write('%s\n' % code)
for data in headers:
stream.write(' %s: %s\n' % data)
stream.flush()
start_response(code, headers)
return application(environ, _start_response)
return _logger
```
The test
```
def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/html')
])
return ['Hello World']
if __name__ == '__main__':
logger = logging_middleware(application)
from wsgiref.simple_server import make_server
httpd = make_server('', 1234, logger)
httpd.serve_forever()
```
See also the [werkzeug debugger](http://werkzeug.pocoo.org/documentation/debug) Armin wrote, it's usefull for interactive debugging.
|
That shouldn't be too hard to write yourself as long as you only need the headers. Try that:
```
import sys
def log_headers(app, stream=None):
if stream is None:
stream = sys.stdout
def proxy(environ, start_response):
for key, value in environ.iteritems():
if key.startswith('HTTP_'):
stream.write('%s: %s\n' % (key[5:].title().replace('_', '-'), value))
return app(environ, start_response)
return proxy
```
|
Debug/Monitor middleware for python wsgi applications
|
[
"",
"python",
"debugging",
"wsgi",
"middleware",
""
] |
I have code like this:
```
var newMsg = new Msg
{
Var1 = var1,
Var2 = var2
};
using (AppDataContext appDataContext = new AppDataContext(ConnectionString))
{
appDataContext.CClass.InsertOnSubmit(newMsg);
appDataContext.SubmitChanges();
}
```
After reading [this post](https://stackoverflow.com/questions/157924/does-linqs-executecommand-provide-protection-from-sql-injection-attacks) I believe that the same logic applies.
Does anyone think that this is subject to SQL Injection Attack?
|
The second answer in the post you're referencing says it:
> LINQ to SQL uses *execute\_sql* with
> parameters.
It does not concatenate property values into a one big INSERT ... VALUES('...', '...')
|
The underlying operation of the DataContext is via the SqlCommand which uses paramatised SQL.
So your insert statement will look like this:
```
INSERT INTO [MSG] [Var1] = @p1, [Var2] = @p2
```
|
Is LINQ to SQL InsertOnSubmit() subject to SQL Injection Attack?
|
[
"",
"c#",
".net",
"linq-to-sql",
"sql-injection",
""
] |
I have several long running report type transactions that take 5-10 minutes. Would I see any performance increase by using stored procs? Would it be significant?
each query runs once a night.
|
The short answer is: no, stored procedures aren't going to improve the performance.
For a start, if you are using parameterised queries there is no difference in performance between a stored procedure and inline SQL. The reason is that ALL queries have cached execution plans - not just stored procedures.
Have a look at <http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx>
If you aren't parameterising your inline queries and you're just building the query up and inserting the 'parameters' as literals then each query will look different to the database and it will need to pre-compile each one. So in this case, you would be doing yourself a favour by using parameters in your inline SQL. And you should do this anyway from a security perspective, otherwise you are opening yourself up to SQL injection attacks.
But anyway the pre-compilation issue is a red herring here. You are talking about long running queries - so long that the pre-compliation is going to be insignificant. So unfortunately, you aren't going to get off easily here. Your solution is going to be to optimise the actual design of your queries, or even to rethink the whole way you are aproaching the task.
|
Probably not. Stored procs give you the advantage of pre-compiled SQL. If your SQL is invoked infrequently, they this advantage will be pretty worthless. So if you have SQL that is expensive because the queries themselves are expensive, then stored procs will gain you no meaningful performance advantage. If you have queries that are invoked very frequently and which themselves execute quickly, then it's worth having a proc.
|
Performance gains in stored procs for long running transactions
|
[
"",
"sql",
"stored-procedures",
""
] |
Assume a table with the following columns:
`pri_id`, `item_id`, `comment`, `date`
What I want to have is a SQL query that will delete any records, for a specific `item_id` that are older than a given date, BUT only as long as there are more than 15 rows for that `item_id`.
This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time. This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records. These are of course arbitrary record counts and date timeframes for this example.
I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc. I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.
|
Something like this should work for you:
```
delete
from
MyTable
where
item_id in
(
select
item_id
from
MyTable
group by
item_id
having
count(item_id) > 15
)
and
Date < @tDate
```
|
You want to keep at least 15 of them always, correct? So:
```
DELETE
FROM CommentTable
WHERE CommentId NOT IN (
SELECT TOP 15 CommentId
FROM CommentTable
WHERE ItemId=@ItemId
AND CommentDate < @Date
ORDER BY CommentDate DESC
)
AND ItemId=@ItemId
AND CommentDate < @Date
```
|
sql statement to delete records older than XXX as long as there are more than YY rows
|
[
"",
"sql",
"datetime",
""
] |
I have a server application that receives information over a network and processes it.
The server is multi-threaded and handles multiple sockets at time, and threads are created without my control through BeginInvoke and EndInvoke style methods, which are chained by corresponding callback functions.
I'm trying to create a form, in addition to the main GUI, that displays a ListBox item populated by items describing the currently connected sockets.
So, what I'm basically trying to do is add an item to the ListBox using its Add() function, from the thread the appropriate callback function is running on.
I'm accessing my forms controls through the Controls property - I.E:
```
(ListBox)c.Controls["listBox1"].Items.Add();
```
Naturally I don't just call the function, I've tried several ways I've found here and on the web to communicate between threads, including `MethodInvoker`, using a `delegate`, in combination with `Invoke()`, `BeginInvoke()` etc.
Nothing seems to work, I always get the same exception telling me my control was accessed from a thread other than the one it was created on.
Any thoughts?
|
You have to call Invoke (or BeginInvoke) on the ListBox control you are accessing in order for the delegate to be called on the thread that created that control.
```
ListBox listBox = c.Controls["listBox1"] as ListBox;
if(listBox != null)
{
listBox.Invoke(...);
}
```
|
I've always used something along these lines:
```
c = <your control>
if (c.InvokeRequired)
{
c.BeginInvoke((MethodInvoker)delegate
{
//do something with c
});
}
else
{
//do something with c
}
```
I also wrote a bunch of helper extension methods to... help.
```
using System;
using System.ComponentModel;
public static class CrossThreadHelper
{
public static bool CrossThread<T,R>(this ISynchronizeInvoke value, Action<T, R> action, T sender, R e)
{
if (value.InvokeRequired)
{
value.BeginInvoke(action, new object[] { sender, e });
}
return value.InvokeRequired;
}
}
```
used like this:
```
private void OnServerMessageReceived(object sender, ClientStateArgs e)
{
if (this.CrossThread((se, ev) => OnServerMessageReceived(se, ev), sender, e)) return;
this.statusTextBox.Text += string.Format("Message Received From: {0}\r\n", e.ClientState);
}
```
|
Need help getting info across a UI thread and another thread in C#
|
[
"",
"c#",
"forms",
"invoke",
"multithreading",
""
] |
Given the following HTML:
```
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
```
How do I grab the string "displayed text 1" using Javascript/the DOM?
|
```
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
```
|
```
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
```
|
How do I access the "displayed" text of a select box option from the DOM?
|
[
"",
"javascript",
"dom",
""
] |
I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control?
```
<div id="formSpinner">
<img src="images/spinner.gif" />
<p>Saving...</p>
</div>
```
|
Add the `runat="server"` attribute to it so you have:
```
<div id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</div>
```
That way you can access the class attribute by using:
```
formSpinner.Attributes["class"] = "classOfYourChoice";
```
It's also worth mentioning that the `asp:Panel` control is virtually synonymous (at least as far as rendered markup is concerned) with `div`, so you could also do:
```
<asp:Panel id="formSpinner" runat="server">
<img src="images/spinner.gif">
<p>Saving...</p>
</asp:Panel>
```
Which then enables you to write:
```
formSpinner.CssClass = "classOfYourChoice";
```
This gives you more defined access to the property and there are others that may, or may not, be of use to you.
|
Make sure that your div is set to runat="server", then simply reference it in the code-behind and set the "class" attribute.
```
<div runat="server" id="formSpinner">
...content...
</div>
```
Code-behind
```
formSpinner.Attributes["class"] = "class-name";
```
|
How to edit CSS style of a div using C# in .NET
|
[
"",
"c#",
".net",
"css",
""
] |
When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?
|
CSS is fine for rollovers. They're implemented basically using the `:hover` pseudo-selector. Here's a really simple implementation:
```
a{
background-image: url(non-hovered-state.png);
}
a:hover{
background-image: url(hovered-state.png);
}
```
There are a few things you need to be aware of though:
* IE6 only supports `:hover` on `<a>` tags
* Images specified in CSS but not used on the page won't be loaded immediately (meaning the rollover state can take a second to appear first time)
The `<a>`-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called [CSS Sprites](http://alistapart.com/articles/sprites/) that can prevent this problem, you can find an example of the technique in use to make [no-preload rollovers](http://www.wellstyled.com/css-nopreload-rollovers.html).
It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using `background-position` so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)):
```
a{
background-image: url(rollover-sprites.png);
background-position: 0 0; /* Added for clarity */
height: 20px;
}
a:hover{
background-position: 0 -20px; /* move the image up 20px to show the hovered state below */
}
```
Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support `background-position`)
|
It will still work in CSS if the browser happens to have Javascript disabled.
|
What is the preferred way to do a CSS rollover?
|
[
"",
"javascript",
"html",
"css",
""
] |
If I create a Stored Procedure in SQL and call it (`EXEC spStoredProcedure`) within the BEGIN/END TRANSACTION, does this stored procedure also fall into the transaction?
I didn't know if it worked like try/catches in C#.
|
Yes, *everything* that you do between the Begin Transaction and Commit (or Rollback) is part of the transaction.
|
Sounds great, thanks a bunch. I ended up doing something like this (because I'm on 05)
```
BEGIN TRY
BEGIN TRANSACTION
DO SOMETHING
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
```
|
Executing a stored procedure inside BEGIN/END TRANSACTION
|
[
"",
"sql",
"sql-server",
"stored-procedures",
"rollback",
"sqltransaction",
""
] |
Examples could be Infragistics or DevExpress.
But I'm also looking for your opinions on other frameworks. It could even be WPF if that is your favorite.
|
Infragistics is very good. I think they have a better product for windows than the web. However, I get very upset using their products sometimes. I just want to find some hidden property, and it is impossible to find. They have way to many properties. Sure, you can do anything with their grid, but it should be easier. All of these vendors are leap frogging each other. You really have to compare all of them every year or two. I am currently using Infragistics on most web and windows project. If I could switch today, I would go to DevExpress for Web and Windows. Everything that Mark Miller and the guys at DevExpress produce is beautiful, and thoughtful. On a side point, you should check out CodeRush and Refacter. I may sound like a salesman, but I am not. I just could no longer code without CodeRush. It would feel like coding with one hand. If you are going to spend $1000 or more on a framework, you should also get CodeRush.
|
I've used Telerik RAD Controls for Asp.Net and it is a very comprehensive suite of controls that are easily converted to AJAX. The support is top notch, with the forum as a first place to go to for research before contacting the staff.
The client side API is fairly easy to understand, and they have good examples of mixed implementations with client and server side code.
|
What is the best 3rd party GUI framework for application development in C#?
|
[
"",
"c#",
".net",
"user-interface",
""
] |
If I do the following:
```
import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
```
I get:
```
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
```
Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?
|
[`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate) documentation:
> Note that if you want to send data to
> the process’s stdin, you need to
> create the Popen object with
> stdin=PIPE. Similarly, to get anything
> other than None in the result tuple,
> you need to give stdout=PIPE and/or
> stderr=PIPE too.
>
> **Replacing os.popen\***
```
pipe = os.popen(cmd, 'w', bufsize)
# ==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
```
> **Warning** Use communicate() rather than
> stdin.write(), stdout.read() or
> stderr.read() to avoid deadlocks due
> to any of the other OS pipe buffers
> filling up and blocking the child
> process.
So your example could be written as follows:
```
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
```
---
On Python 3.5+ (3.6+ for `encoding`), you could use [`subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run), to pass input as a string to an external command and get its exit status, and its output as a string back in one call:
```
#!/usr/bin/env python3
from subprocess import run, PIPE
p = run(['grep', 'f'], stdout=PIPE,
input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# ->
```
|
I figured out this workaround:
```
>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()
```
Is there a better one?
|
How do I pass a string into subprocess.Popen (using the stdin argument)?
|
[
"",
"python",
"subprocess",
"stdin",
""
] |
Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that `WriteLine()` can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code:
```
StreamWriter sw = new StreamWriter(pathToFile);
foreach (GridViewRow record in gv_Records.Rows)
{
string recordInfo = "recordInformation";
sw.WriteLine(recordInfo);
}
```
|
Are you calling StreamWriter.Close() or Flush()?
|
Be sure you wrap your StreamWriter in a using-block, or are careful about your [explicit management of the resource's lifetime](http://msdn.microsoft.com/en-us/library/system.io.streamwriter.close.aspx).
```
using (StreamWriter writer = new StreamWriter(@"somefile.txt"))
{
// ...
writer.WriteLine(largeAmountsOfData);
// ...
}
```
|
Is there a maximum number of characters that can be written using a StreamWriter?
|
[
"",
"c#",
".net",
"file-io",
""
] |
Can I access spring bean that exposed using http invoker (server) from GWT application (client)?
If so is there any example / tutorial for that?
|
There's an application template for Spring-GWT apps available [here](http://bram.jteam.nl/index.php/2007/06/20/springone-2007-slides-sample-code/), that you may find useful. I haven't tried it out, but I believe it's implemented as a Maven archetype.
For more background on exactly what this template does for you, and how to integrate GWT with Spring, check out the following (video) [presentation](http://www.parleys.com/d/142).
|
you can try my way of GWT and Spring integration: <https://code.google.com/p/gspring>.
It's simple and clear.
|
Access spring bean that is exposed using http invoker from GWT application
|
[
"",
"java",
"spring",
"gwt",
""
] |
I've been using jQuery to do the whole AJAX magic in my web based applications.
But I came to a decision that I don’t need all these amazing features jQuery has, except its AJAX functions (like `$.ajax()`, `$.get()`, `$.post`, `getJSON()` and `load();`).
Can you recommend a lightweight crossbrowser AJAX library/framework (up to ~10 kb)?
|
You can make jQuery smaller by removing the modules you don't need / Just modify the [Makefile](https://github.com/jquery/jquery/blob/master/Makefile) file.
|
If you need to use ONLY ajax features take a look at [sajax](http://www.modernmethod.com/sajax/index.phtml) or custom [MooTools](http://mootools.net). Of course, if you are a "lightweight freak" you can write your own routine for this (should be less than 50 lines)
|
Which JavaScript AJAX Framework is most powerful and very lightweight?
|
[
"",
"javascript",
"ajax",
"json",
"frameworks",
""
] |
I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole.
I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share.
I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.
|
There are two main sub-problems one must solve in order to solve this problem:
1. Determine which item is being hovered over
2. Get the MouseHover event to fire when the user has hovered over one item, then moved the cursor within the listbox and hovered over another item.
The first problem is rather simple to solve. By calling a method like the following within your handler for MouseHover, you can determine which item is being hovered over:
```
private ITypeOfObjectsBoundToListBox DetermineHoveredItem()
{
Point screenPosition = ListBox.MousePosition;
Point listBoxClientAreaPosition = listBox.PointToClient(screenPosition);
int hoveredIndex = listBox.IndexFromPoint(listBoxClientAreaPosition);
if (hoveredIndex != -1)
{
return listBox.Items[hoveredIndex] as ITypeOfObjectsBoundToListBox;
}
else
{
return null;
}
}
```
Then use the returned value to set the tool-tip as needed.
The second problem is that normally the MouseHover event isn't fired again until the cursor has left the client area of the control and then come back.
You can get around this by wrapping the `TrackMouseEvent` Win32API call.
In the following code, the `ResetMouseHover` method wraps the API call to get the desired effect: reset the underlying timer that controls when the hover event is fired.
```
public static class MouseInput
{
// TME_HOVER
// The caller wants hover notification. Notification is delivered as a
// WM_MOUSEHOVER message. If the caller requests hover tracking while
// hover tracking is already active, the hover timer will be reset.
private const int TME_HOVER = 0x1;
private struct TRACKMOUSEEVENT
{
// Size of the structure - calculated in the constructor
public int cbSize;
// value that we'll set to specify we want to start over Mouse Hover and get
// notification when the hover has happened
public int dwFlags;
// Handle to what's interested in the event
public IntPtr hwndTrack;
// How long it takes for a hover to occur
public int dwHoverTime;
// Setting things up specifically for a simple reset
public TRACKMOUSEEVENT(IntPtr hWnd)
{
this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT));
this.hwndTrack = hWnd;
this.dwHoverTime = SystemInformation.MouseHoverTime;
this.dwFlags = TME_HOVER;
}
}
// Declaration of the Win32API function
[DllImport("user32")]
private static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);
public static void ResetMouseHover(IntPtr windowTrackingMouseHandle)
{
// Set up the parameter collection for the API call so that the appropriate
// control fires the event
TRACKMOUSEEVENT parameterBag = new TRACKMOUSEEVENT(windowTrackingMouseHandle);
// The actual API call
TrackMouseEvent(ref parameterBag);
}
}
```
With the wrapper in place, you can simply call `ResetMouseHover(listBox.Handle)` at the end of your MouseHover handler and the hover event will fire again even when the cursor stays within the control's bounds.
I'm sure this approach, sticking all the code in the MouseHover handler must result in more MouseHover events firing than are really necessary, but it'll get the job done. Any improvements are more than welcome.
|
Using the MouseMove event, you can keep track of the index of the item that the mouse is over and store this in a variable that keeps its value between MouseMoves. Every time MouseMove is triggered, it checks to see if the index has changed. If so, it disables the tooltip, changes the tooltip text for this control, then re-activates it.
Below is an example where a single property of a Car class is shown in a ListBox, but then full information is shown when hovering over any one row. To make this example work, all you need is a ListBox called lstCars with a MouseMove event and a ToolTip text component called tt1 on your WinForm.
Definition of the car class:
```
class Car
{
// Main properties:
public string Model { get; set; }
public string Make { get; set; }
public int InsuranceGroup { get; set; }
public string OwnerName { get; set; }
// Read only property combining all the other informaiton:
public string Info { get { return string.Format("{0} {1}\nOwner: {2}\nInsurance group: {3}", Make, Model, OwnerName, InsuranceGroup); } }
}
```
Form load event:
```
private void Form1_Load(object sender, System.EventArgs e)
{
// Set up a list of cars:
List<Car> allCars = new List<Car>();
allCars.Add(new Car { Make = "Toyota", Model = "Yaris", InsuranceGroup = 6, OwnerName = "Joe Bloggs" });
allCars.Add(new Car { Make = "Mercedes", Model = "AMG", InsuranceGroup = 50, OwnerName = "Mr Rich" });
allCars.Add(new Car { Make = "Ford", Model = "Escort", InsuranceGroup = 10, OwnerName = "Fred Normal" });
// Attach the list of cars to the ListBox:
lstCars.DataSource = allCars;
lstCars.DisplayMember = "Model";
}
```
The tooltip code (including creating the class level variable called hoveredIndex):
```
// Class variable to keep track of which row is currently selected:
int hoveredIndex = -1;
private void lstCars_MouseMove(object sender, MouseEventArgs e)
{
// See which row is currently under the mouse:
int newHoveredIndex = lstCars.IndexFromPoint(e.Location);
// If the row has changed since last moving the mouse:
if (hoveredIndex != newHoveredIndex)
{
// Change the variable for the next time we move the mouse:
hoveredIndex = newHoveredIndex;
// If over a row showing data (rather than blank space):
if (hoveredIndex > -1)
{
//Set tooltip text for the row now under the mouse:
tt1.Active = false;
tt1.SetToolTip(lstCars, ((Car)lstCars.Items[hoveredIndex]).Info);
tt1.Active = true;
}
}
}
```
|
How can I set different Tooltip text for each item in a listbox?
|
[
"",
"c#",
".net",
"winforms",
"winapi",
"listbox",
""
] |
What aspects of the UpdatePanel are sensitive to time?
I have an UpdatePanel that works fine. If I leave the page for a few minutes and come back, the UpdatePanel doesn't work. Looking at firebug, I see that it sends the Request and gets a Response back. However, the page itself doesn't update. I'm not seeing any script errors either. So far I haven't been able to identify any other factor than the passage of time.
|
Maybe your application domain recycled or your Session was lost. Have you tried seeing what is being called on the server? That'd be my suggestion on where to look next.
|
Turn off Firebug network monitoring if enabled.
|
Why would an UpdatePanel stop working after a few minutes?
|
[
"",
"javascript",
"ajax",
"asp.net-ajax",
"updatepanel",
""
] |
Whats the best practice for setting up package structures in a Java Web Application?
How would you setup your src, unit test code, etc?
|
You could follow maven's [standard project layout](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html). You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,
|
There are a few existing resources you might check:
1. [Properly Package Your Java Classes](http://www.techrepublic.com/article/properly-package-your-java-classes/)
2. [Spring 2.5 Architecture](http://chris.headwaysoftware.com/java/)
3. [Java Tutorial - Naming a Package](http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html)
4. [SUN Naming Conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367)
For what it's worth, my own personal guidelines that I tend to use are as follows:
1. Start with reverse domain, e.g. "com.mycompany".
2. Use product name, e.g. "myproduct". In some cases I tend to have common packages that do not belong to a particular product. These would end up categorized according to the functionality of these common classes, e.g. "io", "util", "ui", etc.
3. After this it becomes more free-form. Usually I group according to project, area of functionality, deployment, etc. For example I might have "project1", "project2", "ui", "client", etc.
A couple of other points:
1. It's quite common in projects I've worked on for package names to flow from the design documentation. Usually products are separated into areas of functionality or purpose already.
2. Don't stress too much about pushing common functionality into higher packages right away. Wait for there to be a need across projects, products, etc., and then refactor.
3. Watch inter-package dependencies. They're not all bad, but it can signify tight coupling between what might be separate units. There are tools that can help you keep track of this.
|
Package structure for a Java project?
|
[
"",
"java",
"package",
""
] |
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.
What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.
PS: [This](https://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly) question/answer deals with the problem in a generic way; how specifically should I solve it?
|
Read up on the try: statement.
```
try:
# do something
except socket.error, e:
# A socket error
except IOError, e:
if e.errno == errno.EPIPE:
# EPIPE error
else:
# Other error
```
|
Assuming that you are using the standard socket module, you should be catching the `socket.error: (32, 'Broken pipe')` exception (not IOError as others have suggested). This will be raised in the case that you've described, i.e. sending/writing to a socket for which the remote side has disconnected.
```
import socket, errno, time
# setup socket to listen for incoming connections
s = socket.socket()
s.bind(('localhost', 1234))
s.listen(1)
remote, address = s.accept()
print "Got connection from: ", address
while 1:
try:
remote.send("message to peer\n")
time.sleep(1)
except socket.error, e:
if isinstance(e.args, tuple):
print "errno is %d" % e[0]
if e[0] == errno.EPIPE:
# remote peer disconnected
print "Detected remote disconnect"
else:
# determine and handle different error
pass
else:
print "socket error ", e
remote.close()
break
except IOError, e:
# Hmmm, Can IOError actually be raised by the socket module?
print "Got IOError: ", e
break
```
Note that this exception will not always be raised on the first write to a closed socket - more usually the second write (unless the number of bytes written in the first write is larger than the socket's buffer size). You need to keep this in mind in case your application thinks that the remote end received the data from the first write when it may have already disconnected.
You can reduce the incidence (but not entirely eliminate) of this by using `select.select()` (or `poll`). Check for data ready to read from the peer before attempting a write. If `select` reports that there is data available to read from the peer socket, read it using `socket.recv()`. If this returns an empty string, the remote peer has closed the connection. Because there is still a race condition here, you'll still need to catch and handle the exception.
Twisted is great for this sort of thing, however, it sounds like you've already written a fair bit of code.
|
How to handle a broken pipe (SIGPIPE) in python?
|
[
"",
"python",
"python-2.x",
"broken-pipe",
""
] |
I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore.
There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain `#includes` if the file didn't exist in the current folder. Does anyone know a way to achieve that?
Presently, we use an `#ifdef` around the `#include` in the shared file, with a second project-specific file that #defines whether or not the `#include` exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas?
|
Generally this is done by using a script that tries running the preprocessor on an attempt at including the file. Depending on if the preprocessor returns an error, the script updates a generated .h file with an appropriate #define (or #undef). In bash, the script might look vaguely like this:
```
cat > .test.h <<'EOM'
#include <asdf.h>
EOM
if gcc -E .test.h
then
echo '#define HAVE_ASDF_H 1' >> config.h
else
echo '#ifdef HAVE_ASDF_H' >> config.h
echo '# undef HAVE_ASDF_H' >> config.h
echo '#endif' >> config.h
fi
```
A pretty thorough framework for portably working with portability checks like this (as well as thousands others) is [autoconf](http://www.gnu.org/software/autoconf/).
|
# Little Update
Some compilers might support `__has_include ( header-name )`.
The extension was added to the [C++17 standard](https://isocpp.org/files/papers/p0636r0.html) ([P0061R1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0061r1.html)).
## Compiler Support
* Clang
* GCC from 5.X
* Visual Studio from VS2015 Update 2 (?)
## Example (from clang website):
```
// Note the two possible file name string formats.
#if __has_include("myinclude.h") && __has_include(<stdint.h>)
# include "myinclude.h"
#endif
```
# Sources
* [SD-6: SG10 Feature Test Recommendations](https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations)
* [Clang Language Extensions](http://clang.llvm.org/docs/LanguageExtensions.html#langext-has-include)
|
Can the C preprocessor be used to tell if a file exists?
|
[
"",
"c++",
"include",
"c-preprocessor",
""
] |
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.
The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:
```
doSomething int double
doSomethingElse java.lang.String boolean
```
If the input was something like `java.lang.String`, I know I could use `Class.forName("java.lang.String")` to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?
**Edit:**
Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the `ClassUtils` class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.
|
The Spring framework contains a utility class [ClassUtils](http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/util/ClassUtils.html) which contains the static method forName. This method can be used for the exact purpose you described.
In case you don’t like to have a dependency on Spring: the [source code of the method](https://github.com/spring-projects/spring-framework/blob/cc74a2891a4d2a4c7bcec059f20c35aa80bcf668/spring-core/src/main/java/org/springframework/util/ClassUtils.java#L203-L271) can be found ~~e. g. [here](http://fisheye1.atlassian.com/browse/springframework/spring/src/org/springframework/util/ClassUtils.java?r=1.77)~~ on their public repository. The class source code is licensed under the Apache 2.0 model.
Note however that the algorithm uses a hard-coded map of primitive types.
---
**Edit:** Thanks to commenters Dávid Horváth and Patrick for pointing out the broken link.
|
The `Class` instances for the primitive types are obtainable as you said using e.g. `int.class`, but it is also possible to get the same values using something like `Integer.TYPE`. Each primitive wrapper class contains a static field, `TYPE`, which has the corresponding primitive class instance.
You cannot obtain the primitive class via `forName`, but you can get it from a class which is readily available. If you absolutely must use reflection, you can try something like this:
```
Class clazz = Class.forName("java.lang.Integer");
Class intClass = clazz.getField("TYPE").get(null);
intClass.equals(int.class); // => true
```
|
Dynamically find the class that represents a primitive Java type
|
[
"",
"java",
"reflection",
"types",
"primitive",
""
] |
I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document?
```
<script type="text/javascript">
$(document).ready(function() {
// ???
});
</script>
```
|
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.
```
<script type="text/javascript">
$(document).ready(function() {
document.title = 'blah';
});
</script>
```
|
Do not use `$('title').text('hi')`, because IE doesn't support it.
It is better to use `document.title = 'new title';`
|
How can I change the title of the document during .ready()?
|
[
"",
"javascript",
"jquery",
"ruby-on-rails",
""
] |
I'm looking to utilize jQuery to handle a few very common requests we get for data tables of varying sizes: scrolling, sorting, and dynamic filtering.
* I've handled scrolling in the past by having two separate tables with fixed width columns, along with associated div containers for the "actual" scrolling. However, this method doesn't work with any of the jQuery-based sorting table extensions that I've come across (tablesorter being my favorite so far) as they want everything in a single table.
* For filtering, they're requesting something akin to how Excel and SharePoint lists do it (basically all column values are listed in a dropdown, allowing the user to select/deselect them). I haven't seen anything like that yet, although it sounds possible.
* One other related nice-to-have feature would be the ability to "freeze" a column for horizontal scrolling.
Ideally I'd like an existing extenstion, but if none are out there I'd also appreciate suggestions from any jQuery gurus on how to best implement it. My current thoughts are to dive into tablesorter and extend/update it as necessary.
To hopefully keep things focused, paging is not an option (along with anything server based, for that matter).
**Update:**
I do appreciate the answers so far, but none of the options given so far touch on the filtering aspect at all (that said, I must admit that jqGrid looks very good for some future projects I have). In the meantime I'll work on a custom filtering solution; if it works out I'll update again.
|
I came across this question as I was searching for a sortable table plugin myself; I really wasn't impressed with any of the suggested widgets, but later I discovered [DataTables](http://datatables.net/index), and I was quite impressed. I recommend checking it out.
|
Maybe this excellent plug-in could do it:
[Demo page](http://trirand.com/jqgrid/jqgrid.html)
It's called jQGrid, here is the project page:
<http://plugins.jquery.com/project/jqGrid>
|
jQuery Scrollable, Sortable, Filterable table
|
[
"",
"javascript",
"jquery",
"html",
""
] |
How does one write a unit test that fails only if a function doesn't throw an expected exception?
|
Use [`TestCase.assertRaises`](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises) from the `unittest` module, for example:
```
import mymod
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc)
```
|
Since Python 2.7 you can use context manager to get ahold of the actual Exception object thrown:
```
import unittest
def broken_function():
raise Exception('This is broken')
class MyTestCase(unittest.TestCase):
def test(self):
with self.assertRaises(Exception) as context:
broken_function()
self.assertTrue('This is broken' in context.exception)
if __name__ == '__main__':
unittest.main()
```
*[assertRaises](http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises)*
---
In **Python 3.5**, you have to wrap `context.exception` in `str`, otherwise you'll get a `TypeError`
```
self.assertTrue('This is broken' in str(context.exception))
```
|
How do you test that a Python function throws an exception?
|
[
"",
"python",
"unit-testing",
"exception",
""
] |
I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly).
As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds.
Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers.
Thanks in advance for any help with this.
Code Sample Below (The Difference in in the first line of the query at the end (fk\_source vs. fk \_Source):
```
//Original
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn);
//Rebuilt
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn);
```
|
I suspect that this is a procedure cache issue. One benefit of stored procedures is that the plan is stored for you, which speeds things up. Unfortunately, it's possible to get a bad plan in the cache (even when using dynamic queries).
Just for fun, I checked my procedure cache, ran an adhoc query, checked again, then I ran the same query with different capitlization and I was surprised to see the procedure count higher.
Try this....
Connect to SQL Server Management Studio.
```
DBCC MemoryStatus
Select Columns... From TABLES.... Where....
dbcc MemoryStatus
Select Columns... From tables.... Where....
dbcc MemoryStatus
```
I think you'll find that the TotalProcs changes when the statement changes (even when the only change is case sensitive).
Updating your statistics may help. That is a rather slow running process, so you may want to run that during a slow period.
|
Since you are using SQL Server 2005, have you tried with a SqlCommand object instead of the OleDbCommand object?
|
Case Sensitivity when querying SQL Server 2005 from .NET using OleDB
|
[
"",
"c#",
".net",
"sql-server",
"oledb",
"case-sensitive",
""
] |
PHP 4.4 and PHP 5.2.3 under Apache 2.2.4 on ubuntu.
I am running Moodle 1.5.3 and have recently had a problem when updating a course. The $\_POST variable is empty but only if a lot of text was entered into the textarea on the form. If only a short text is entered it works fine.
I have increased the post\_max\_size from 8M to 200M and increased the memory\_limit to 256M but this has not helped.
I have doubled the LimitRequestFieldSize and LimitRequestLine to 16380 and set LimitRequestBody to 0 with no improvement.
I have googled for an answer but have been unable to find one.
HTTP Headers on firefox shows the content size of 3816 with the correct data, so its just not getting to $\_POST.
The system was running fine until a few weeks ago. The only change was to /etc/hosts to correct a HELO issue with the exim4 email server.
I can replicate the issue on a development machine that has exim4 not running so I think it is just coincidence.
Thanks for your assistance.
|
Could it be not the size related of the post, but how long the line is before a new line. If they use the Moodle WYSIWYG view the html would just get put into one line with no breaks. If you go into html and hit return around every 1000 characters does it work?
|
I don't know enough to really provide a useful answer so the following is more a well-educated guess (at least I hope so).
First, you should debug the entire request, either by access\_log or for example through [firebug](http://www.getfirebug.com/). (Good to have Firebug anyway.) To me your problem *sounds* like a redirect happens in between. I give you an example:
Assume this is your structure:
```
/form.php
/directory/index.php
```
This is your form:
```
<form action="/directory" method="post">
...
</form>
```
Problem in this case is, that even though `/directory` is a valid url, Apache will redirect you one more time to `/directory/`, thus you are loosing your payload (what is supposed to be in `$_POST`).
|
Why is _POST sometimes empty when a textarea is posted in PHP
|
[
"",
"php",
"apache2",
""
] |
When I get a java.io.InvalidClassException, it gives me the serialVersionUID that it wants, and the serialVersionUID that it got. Is there an easy way to tell which of my dozens of jars using the wrong serialVersionUID?
**Update**: I should mention that our intention is to update everything at the same time, but I'm trying to debug a problem in our build and deploy process.
|
use the serialver tool from the sun jdk for each class in the jar.
|
The best way to deal with this kind of trouble is to update jars on the server and client side at the same time. This will guarantee the same version of your classes on both sides and you'll not have trouble when serializing / deserializing. Tracking serial UIDs each time you have this problem is not going to solve anything, you're only going to waste considerable time and resources. Its much better to spend some time and implement a proper deployment / packaging strategy.
If you really don't have any other choice, you can write a tool that loads a class from each jar (using a URLClassLoader) and then use `java.io.ObjectStreamClass.getSerialVersionUID()` to obtain the information you need.
|
Find which class in which jar has a given serialVersionUID
|
[
"",
"java",
"serialversionuid",
""
] |
In C#, what is the best way to access a property of the derived class when the generic list contains just the base class.
```
public class ClassA : BaseClass
{
public object PropertyA { get; set; }
}
public class ClassB: BaseClass
{
public object PropertyB { get; set; }
}
public class BaseClass
{
}
public void Main
{
List<BaseClass> MyList = new List<BaseClass>();
ClassA a = new ClassA();
ClassB b = new ClassB();
MyList.Add(a);
MyList.Add(b);
for(int i = 0; i < MyList.Count; i++)
{
//I would like to access PropertyA abd PropertyB from the derived classes
}
}
```
|
Certainly you can downcast, like so:
```
for (int i = 0; i < MyList.Count; i++)
{
if (MyList[i] is ClassA)
{
var a = ((ClassA)MyList[i]).PropertyA;
// do stuff with a
}
if (MyList[i] is ClassB)
{
var b = ((ClassB)MyList[i]).PropertyB;
// do stuff with b
}
}
```
... However, you should take another look at what you're trying to accomplish. If you have common code that needs to get to properties of ClassA and ClassB, then you may be better off wrapping access to those properties up into a shared, virtual property or method in the ancestor class.
Something like:
```
public class BaseClass
{
public virtual void DoStuff() { }
}
public class ClassA : BaseClass
{
public object PropertyA { get; set; }
public override void DoStuff()
{
// do stuff with PropertyA
}
}
public class ClassB : BaseClass
{
public object PropertyB { get; set; }
public override void DoStuff()
{
// do stuff with PropertyB
}
}
```
|
Further to TimJ's answer, you can write one extension method that will work for all types:
```
public static IEnumerable<T> OfType<T>(this IEnumerable list)
{
foreach (var obj in list)
{
if (obj is T)
yield return (T)obj;
}
}
```
Or if you have Linq, that function is in the namespace System.Linq.
|
Accessing a property of derived class from the base class in C#
|
[
"",
"c#",
"generics",
"collections",
""
] |
I have a specialized list that holds items of type `IThing`:
```
public class ThingList : IList<IThing>
{...}
public interface IThing
{
Decimal Weight { get; set; }
Decimal Velocity { get; set; }
Decimal Distance { get; set; }
Decimal Age { get; set; }
Decimal AnotherValue { get; set; }
[...even more properties and methods...]
}
```
Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out:
```
public class ThingList : IList<IThing>
{
public Decimal GetMaximumWeight()
{
Decimal result = 0;
foreach (IThing thing in this) {
result = Math.Max(result, thing.Weight);
}
return result;
}
}
```
Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a `GetMaximum*()/GetMinimum*()` pair for every single property.
One solution would be reflection. Something like (hold your nose, strong code smell!):
```
Decimal GetMaximum(String propertyName);
Decimal GetMinimum(String propertyName);
```
Are there any better, less smelly ways to accomplish this?
Thanks,
Eric
Edit: @Matt: .Net 2.0
Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys.
Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful.
I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately.
Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-)
|
Yes, you should use a delegate and anonymous methods.
For an example see [here](http://encodo.com/en/blogs.php?entry_id=76).
Basically you need to implement something similar to the [Find method of Lists](http://msdn.microsoft.com/en-us/library/x0b5b5bc(VS.80).aspx).
Here is a sample implementation
```
public class Thing
{
public int theInt;
public char theChar;
public DateTime theDateTime;
public Thing(int theInt, char theChar, DateTime theDateTime)
{
this.theInt = theInt;
this.theChar = theChar;
this.theDateTime = theDateTime;
}
public string Dump()
{
return string.Format("I: {0}, S: {1}, D: {2}",
theInt, theChar, theDateTime);
}
}
public class ThingCollection: List<Thing>
{
public delegate Thing AggregateFunction(Thing Best,
Thing Candidate);
public Thing Aggregate(Thing Seed, AggregateFunction Func)
{
Thing res = Seed;
foreach (Thing t in this)
{
res = Func(res, t);
}
return res;
}
}
class MainClass
{
public static void Main(string[] args)
{
Thing a = new Thing(1,'z',DateTime.Now);
Thing b = new Thing(2,'y',DateTime.Now.AddDays(1));
Thing c = new Thing(3,'x',DateTime.Now.AddDays(-1));
Thing d = new Thing(4,'w',DateTime.Now.AddDays(2));
Thing e = new Thing(5,'v',DateTime.Now.AddDays(-2));
ThingCollection tc = new ThingCollection();
tc.AddRange(new Thing[]{a,b,c,d,e});
Thing result;
//Max by date
result = tc.Aggregate(tc[0],
delegate (Thing Best, Thing Candidate)
{
return (Candidate.theDateTime.CompareTo(
Best.theDateTime) > 0) ?
Candidate :
Best;
}
);
Console.WriteLine("Max by date: {0}", result.Dump());
//Min by char
result = tc.Aggregate(tc[0],
delegate (Thing Best, Thing Candidate)
{
return (Candidate.theChar < Best.theChar) ?
Candidate :
Best;
}
);
Console.WriteLine("Min by char: {0}", result.Dump());
}
}
```
The results:
`Max by date: I: 4, S: w, D: 10/3/2008 12:44:07 AM`
`Min by char: I: 5, S: v, D: 9/29/2008 12:44:07 AM`
|
(Edited to reflect .NET 2.0 answer, and LINQBridge in VS2005...)
There are three situations here - although the OP only has .NET 2.0, other people facing the same problem may not...
1) Using .NET 3.5 and C# 3.0: use LINQ to Objects like this:
```
decimal maxWeight = list.Max(thing => thing.Weight);
decimal minWeight = list.Min(thing => thing.Weight);
```
2) Using .NET 2.0 and C# 3.0: use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) and the same code
3) Using .NET 2.0 and C# 2.0: use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) and anonymous methods:
```
decimal maxWeight = Enumerable.Max(list, delegate(IThing thing)
{ return thing.Weight; }
);
decimal minWeight = Enumerable.Min(list, delegate(IThing thing)
{ return thing.Weight; }
);
```
(I don't have a C# 2.0 compiler to hand to test the above - if it complains about an ambiguous conversion, cast the delegate to Func<IThing,decimal>.)
LINQBridge will work with VS2005, but you don't get extension methods, lambda expressions, query expressions etc. Clearly migrating to C# 3 is a nicer option, but I'd prefer using LINQBridge to implementing the same functionality myself.
All of these suggestions involve walking the list twice if you need to get both the max and min. If you've got a situation where you're loading from disk lazily or something like that, and you want to calculate several aggregates in one go, you might want to look at my ["Push LINQ"](http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx) code in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil). (That works with .NET 2.0 as well.)
|
C#: Getting maximum and minimum values of arbitrary properties of all items in a list
|
[
"",
"c#",
".net",
"reflection",
".net-2.0",
""
] |
I want to know how to use variables for objects and function names in Python. In PHP, you can do this:
```
$className = "MyClass";
$newObject = new $className();
```
How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
|
In Python,
```
className = MyClass
newObject = className()
```
The first line makes the variable `className` refer to the same thing as `MyClass`. Then the next line calls the `MyClass` constructor through the `className` variable.
As a concrete example:
```
>>> className = list
>>> newObject = className()
>>> newObject
[]
```
(In Python, `list` is the constructor for the `list` class.)
The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you *must* use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.
|
Assuming that some\_module has a class named "class\_name":
```
import some_module
klass = getattr(some_module, "class_name")
some_object = klass()
```
I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in this situation. :)
One other method (assuming that we still are using "class\_name"):
```
class_lookup = { 'class_name' : class_name }
some_object = class_lookup['class_name']() #call the object once we've pulled it out of the dict
```
The latter method is probably the most secure way of doing this, so it's probably what you should use if at all possible.
|
Using Variables for Class Names in Python?
|
[
"",
"python",
"dynamic-typing",
""
] |
I would like to know many minutes between 2 dates?
Example : Now - tommorow at the exact time would return me 1440.
|
```
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1);
int diff = dt2.Subtract(dt1).TotalMinutes;
```
|
Look at the TimeSpan class.
```
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(1);
TimeSpan diff = date2.Subtract(date1);
Console.WriteLine(diff.Minutes);
```
|
Exact time between 2 DateTime?
|
[
"",
"c#",
".net",
"datetime",
".net-2.0",
""
] |
I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P )
I understand C and Java very well.
```
TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
{
int bla;
int bla;
}
```
As far I can "deduce" The first line only declares the construtor name, the "::" sounds like "belongs to" to me. And the code between {} is the constructor body it self.
I "think" what's after the paremeters and the first "{" are like methods default parameters or something, but I don't find a reasonable explanation on the web. Most of the C++ constructors that I found in the examples are almost identical to those in Java.
I'm I right in my assumptions? "::" is like belongs to, and the list after params and body are like "default args" or something?
**UPDATE:**
Thanks for the answers.
May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body
|
The most common case is this:
```
class foo{
private:
int x;
int y;
public:
foo(int _x, int _y) : x(_x), y(_y) {}
}
```
This will set `x` and `y` to the values that are given in `_x` and `_y` in the constructor parameters. This is often the best way to construct any objects that are declared as data members.
It is also possible that you were looking at constructor chaining:
```
class foo : public bar{
foo(int x, int y) : bar(x, y) {}
};
```
In this instance, the class's constructor will call the constructor of its base class and pass the values `x` and `y`.
To dissect the function even further:
```
TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
{
int bla;
int bla;
}
```
The `::`-operator is called the scope resolution operator. It basically just indicates that `TransparentObject` is a member of `TransparentObject`. Secondly, you are correct in assuming that the body of the constructor occurs in the curly braces.
> UPDATE: Thanks for the answers. May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body
There is much more information on this subject than I could possibly ever give you [here](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6). The most common area where you have to use initializer lists is when you're initializing a reference or a `const` as these variables must be given a value immediately upon creation.
|
You are pretty close. The first line is the declaration. The label left of the :: is the class name and for it to be a constructor, the function name has to be the same as the class name.
```
TransparentObject::TransparentObject( int w, int x, int y, int z )
```
In C++ you can optionally put a colon and some initial values for member variables before the start of the function body. This technique must be used if you are initialzing any **const** variables or passing parameters to a superclass constructor.
```
:
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
```
And then comes the body of the constructor in curly braces.
```
{
int bla;
int bla;
}
```
|
What is the member variables list after the colon in a constructor good for?
|
[
"",
"c++",
"constructor",
""
] |
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.
Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2\*\*32]?
In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.
EDIT: the specific issue is this:
```
>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
```
|
You can mask everything by `0xFFFFFFFF`:
```
>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
```
|
You can use [ctypes](http://docs.python.org/lib/module-ctypes.html) and its `c_uint32`:
```
>>> import ctypes
>>> m = 0xFFFFFF00
>>> ctypes.c_uint32(~m).value
255L
```
So what I did here was casting `~m` to a C 32-bit unsigned integer and retrieving its value back in Python format.
|
Python: unsigned 32 bit bitwise arithmetic
|
[
"",
"python",
"math",
""
] |
Is it really necessary to release COM components from Office PIA, when you don't need them anymore by invoking Marshal.ReleaseComObject(..)?
I found various and contradictory advices on this topic on the web. In my opinion, since Outlook PIA is always returning a new references to its interfaces as returning values from its methods, it is not necessary to explicitly release it. Am I right?
|
With Microsoft Office, in general, you do need to explicitly release your references, which can be safely done in two stages:
(1) First release all the minor object to which you do not hold a named object variable via a call to GC.Collect() and then GC.WaitForPendingFinalizers(). (You need to call this twice, if the objects involved could have finalizers, such as when using Visual Studio Tools for Office (VSTO).)
(2) Then explicitly release the objects to which you hold a named variable via a call to Marshall.FinalReleaseComObject() on each object.
That's it. :-)
I discussed this in more detail [in a previous post](https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c#159419), along with a code example.
|
For VS 2010, see [Marshal.ReleaseComObject Is Considered Dangerous](http://www.infoq.com/news/2010/03/ReleaseComObject-Dangerous).
|
Release COM Components
|
[
"",
"c#",
".net",
"outlook",
"add-in",
"pia",
""
] |
I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:
```
DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);
```
I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.
What can I do?
Update
I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the [forum](http://forums.sun.com/thread.jspa?messageID=2054303#2699961) pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes
|
‘IgnoringElementContentWhitespace’ is not about removing *all* pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text.
If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)
You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the < !DOCTYPE ... [...] > declaration containing < !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.
Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.
|
This is a (really) late answer, but here is how I solved it. I wrote my own implementation of a `NodeList` class. It simply ignores text nodes that are empty. Code follows:
```
private static class NdLst implements NodeList, Iterable<Node> {
private List<Node> nodes;
public NdLst(NodeList list) {
nodes = new ArrayList<Node>();
for (int i = 0; i < list.getLength(); i++) {
if (!isWhitespaceNode(list.item(i))) {
nodes.add(list.item(i));
}
}
}
@Override
public Node item(int index) {
return nodes.get(index);
}
@Override
public int getLength() {
return nodes.size();
}
private static boolean isWhitespaceNode(Node n) {
if (n.getNodeType() == Node.TEXT_NODE) {
String val = n.getNodeValue();
return val.trim().length() == 0;
} else {
return false;
}
}
@Override
public Iterator<Node> iterator() {
return nodes.iterator();
}
}
```
You then wrap all of your `NodeList`s in this class and it will effectively ignore all whitespace nodes. (Which I define as Text Nodes with 0-length trimmed text.)
It also has the added benefit of being able to be used in a for-each loop.
|
How to ignore whitespace while reading a file to produce an XML DOM
|
[
"",
"java",
"xml",
"whitespace",
""
] |
I'd like to make a click event fire on an `<input type="file">` tag programmatically.
Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.
I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.
|
You cannot do that in all browsers, supposedly IE *does* allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that *is* a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.
|
I have been searching for solution to this whole day. And these are the conclusions that I have made:
1. For the security reasons Opera and Firefox don't allow to trigger file input.
2. The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it. In this way the button is seen but on user click it actually activates the file input.
Upload File
|
In JavaScript can I make a "click" event fire programmatically for a file input element?
|
[
"",
"javascript",
"html",
""
] |
I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine:
1. Right-click on the desktop and select Properties.
2. Click on the Appearance Tab.
3. Select the Font Size: Normal/Large Fonts/Extra Large Fonts
My understanding is that the font size change results in a DPI change, so here is what I've tried so far.
---
## My Goal:
I want to detect when the **Windows Font Size** has changed from Normal to Large or Extra Large Fonts and take some actions based on that font size change. I assume that when the Windows Font Size changes, the DPI will also change (especially when the size is Extra Large Fonts
---
## What I've tried so far:
I receive several messages including: WM\_SETTINGCHANGE, WM\_NCCALCSIZE, WM\_NCPAINT, etc... but none of these messages are unique to the situation when the font size changes, in other words, when I receive the WM\_SETTINGSCHANGE message I want to know what changed.
In theory when I define the OnSettingChange and Windows calls it, the lpszSection should tell me what the changing section is, and that works fine, but then I check the given section by calling SystemParametersInfo and I pass in the action SPI\_GETNONCLIENTMETRICS, and I step through the debugger and I make sure that I watch the data in the returned NONCLIENTMETRICS for any font changes, but none occur.
Even if that didn't work, I should still be able to check the DPI when the Settings change. I really wouldn't care about the other details, every time I get the WM\_SETTINGCHANGE message, I would just check the DPI and perform the actions I'm interested in performing, but I'm not able to get the system DPI either.
I have tried to get the DPI by invoking the method GetSystemMetrics, also for each DC:
Dekstop DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Window DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Current DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Even if I change the DPI in the Graphic Properties Window these values don't return anything different, they always show 96.
Could anybody help me figure this out please? What should I be looking for? Where should I be looking at?
```
afx_msg void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
int windowDPI = 0;
int deviceDPI = 0;
int systemDPI = 0;
int desktopDPI = 0;
int dpi_00_X = 0;
int dpi_01_X = 0;
int dpi_02_X = 0;
int dpi_03_X = 0;
CDC* windowDC = CWnd::GetWindowDC(); // try with window DC
HDC desktop = ::GetDC(NULL); // try with desktop DC
CDC* device = CWnd::GetDC(); // try with current DC
HDC hDC = *device; // try with HDC
if( windowDC )
{
windowDPI = windowDC->GetDeviceCaps(LOGPIXELSY);
// always 96 regardless if I change the Font
// Size to Extra Large Fonts or keep it at Normal
dpi_00_X = windowDC->GetDeviceCaps(LOGPIXELSX); // 96
}
if( desktop )
{
desktopDPI = ::GetDeviceCaps(desktop, LOGPIXELSY); // 96
dpi_01_X = ::GetDeviceCaps(desktop, LOGPIXELSX); // 96
}
if( device )
{
deviceDPI = device->GetDeviceCaps(LOGPIXELSY); // 96
dpi_02_X = device->GetDeviceCaps(LOGPIXELSX); // 96
}
systemDPI = ::GetDeviceCaps(hDC, LOGPIXELSY); // 96
dpi_03_X = ::GetDeviceCaps(hDC, LOGPIXELSX); // 96
CWnd::ReleaseDC(device);
CWnd::ReleaseDC(windowDC);
::ReleaseDC(NULL, desktop);
::ReleaseDC(NULL, hDC);
CWnd::OnWinSettingChange(uFlags, lpszSection);
}
```
The DPI always returns 96, but the settings changes DO take effect when I change the font size to Extra Large Fonts or if I change the DPI to 120 (from the graphics properties).
|
[EDIT after re-read] I'm almost positive that changing to "Large fonts" does not cause a DPI change, rather it's a theme setting. You should be able to verify by applying the "Large fonts" change and then opening the advanced display properties where the DPI setting lives, it should have remained at 96dpi.
---
DPI change is supposed to require a reboot. Maybe the setting hasn't propagated to a place where GetDeviceCaps can retrieve it?
Maybe try changing a non-reboot-requiring setting (resolution perhaps) and then see if you can detect the change. If you can, your answer is probably that you can't detect DPI change until after reboot.
|
When you call GetDeviceCaps() on the Desktop DC, are you perhaps using a DC that might be cached by MFC, and therefore contains out-of-date information? Are you making the GetDeviceCaps() call synchronously from inside your OnSettingsChange handler? I could see how either or both of these things might get you an out of date version of DPI.
Raymond Chen [wrote about this](https://devblogs.microsoft.com/oldnewthing/20040714-00/?p=38443) and his solution looked like this (Note that I've added :: operators to avoid calling the MFC wrappers of the APIs):
```
int GetScreenDPI()
{
HDC hdcScreen = ::GetDC(NULL);
int iDPI = -1; // assume failure
if (hdcScreen) {
iDPI = ::GetDeviceCaps(hdcScreen, LOGPIXELSX);
::ReleaseDC(NULL, hdcScreen);
}
return iDPI;
}
```
|
Can't detect when Windows Font Size has changed C++ MFC
|
[
"",
"c++",
"winapi",
"mfc",
"font-size",
"system-font",
""
] |
I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.
```
string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);
```
The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.
I'm looking for a function that will validate an image given a stream or a file path of the image.
Example function prototype
```
bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);
```
|
JPEG's don't have a formal header definition, but they do have a small amount of metadata you can use.
* Offset 0 (Two Bytes): JPEG SOI marker (FFD8 hex)
* Offset 2 (Two Bytes): Image width in pixels
* Offset 4 (Two Bytes): Image height in pixels
* Offset 6 (Byte): Number of components (1 = grayscale, 3 = RGB)
There are a couple other things after that, but those aren't important.
You can open the file using a binary stream, and read this initial data, and make sure that OffSet 0 is 0, and OffSet 6 is either 1,2 or 3.
That would at least give you slightly more precision.
Or you can just trap the exception and move on, but I thought you wanted a challenge :)
|
here is my image check. I cannot rely on file extensions and have to check the format on my own.
I am loading BitmapImages in WPF from byte arrays and don't know the format upfront. WPF detects the format fine but does not tell you the image format of BitmapImage objects (at least I am not aware of a property for this). And I don't want load the image again with System.Drawing only to detect the format. This solution is fast and works fine for me.
```
public enum ImageFormat
{
bmp,
jpeg,
gif,
tiff,
png,
unknown
}
public static ImageFormat GetImageFormat(byte[] bytes)
{
// see http://www.mikekunz.com/image_file_header.html
var bmp = Encoding.ASCII.GetBytes("BM"); // BMP
var gif = Encoding.ASCII.GetBytes("GIF"); // GIF
var png = new byte[] { 137, 80, 78, 71 }; // PNG
var tiff = new byte[] { 73, 73, 42 }; // TIFF
var tiff2 = new byte[] { 77, 77, 42 }; // TIFF
var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg
var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon
if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
return ImageFormat.bmp;
if (gif.SequenceEqual(bytes.Take(gif.Length)))
return ImageFormat.gif;
if (png.SequenceEqual(bytes.Take(png.Length)))
return ImageFormat.png;
if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
return ImageFormat.tiff;
if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
return ImageFormat.tiff;
if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
return ImageFormat.jpeg;
if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
return ImageFormat.jpeg;
return ImageFormat.unknown;
}
```
|
Validate image from file in C#
|
[
"",
"c#",
".net",
"image",
"file-io",
""
] |
I have a String which I would like to modify in some way. For example: reverse it or upcase it.
I have discovered that the fastest way to do this is by using a unsafe block and pointers.
For example:
```
unsafe
{
fixed (char* str = text)
{
*str = 'X';
}
}
```
Are there any reasons why I should never ever do this?
|
The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations.
[String interning](http://en.wikipedia.org/wiki/String_intern_pool) is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumption) the .Net framework maintains a Dictionary of pointers, all pre-defined strings will live in this dictionary or any strings where you call the `String.intern` method on. When the IL instruction ldstr is called it will check the interned dictionary and avoid memory allocation if we already have the string allocated, note: [String.Concat](http://bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx) will not check for interned strings.
This property of the .net framework means that if you start mucking around directly with strings you can corrupt your intern table and in turn corrupt other references to the same string.
For example:
```
// these strings get interned
string hello = "hello";
string hello2 = "hello";
string helloworld, helloworld2;
helloworld = hello;
helloworld += " world";
helloworld2 = hello;
helloworld2 += " world";
unsafe
{
// very bad, this changes an interned string which affects
// all app domains.
fixed (char* str = hello2)
{
*str = 'X';
}
fixed (char* str = helloworld2)
{
*str = 'X';
}
}
Console.WriteLine("hello = {0} , hello2 = {1}", hello, hello2);
// output: hello = Xello , hello2 = Xello
Console.WriteLine("helloworld = {0} , helloworld2 = {1}", helloworld, helloworld2);
// output : helloworld = hello world , helloworld2 = Xello world
```
|
> Are there any reasons why I should never ever do this?
Yes, very simple: Because .NET relies on the fact that strings are immutable. Some operations (e.g. `s.SubString(0, s.Length)`) actually return a reference to the original string. If this now gets modified, all other references will as well.
Better use a `StringBuilder` to modify a string since this is the default way.
|
Why should I never use an unsafe block to modify a string?
|
[
"",
"c#",
".net",
""
] |
If we are writing about power-wise option - is using a console-based application in C#(.NET) better than having Windows GUI and what's the real difference expept few libraries loaded in operational memory?
The issue is about text comparisons and working with strings, connecting to Internet, gathering data, working with database.
I meant power-capability, but as I've read here, it's more about controls than any power-relation. Thx :)
|
From your description it seems that you want to write an HTML scraping software or some kind of web spider. I think your decision whether to write a GUI or a command line application should depend on who (users) or which other software components will use or integrate your program.
If there is no user interaction involved, I guess it would be just fine to write it as command line program. If you have some options to set you could pass them as arguments.
If it will be a recurring, isolated job, you could also consider writing the application as **windows service**, which could start with the machine.
|
I'm not entirely sure what your requirements are. GUIs tend to be harder to write than console apps, but open up a great level of usability (if you design them well, which is another matter entirely).
If it's a simple tool that doesn't really need interactivity: start with some command line arguments, process and report progress, finish - then I'd write a console app. If more interactivity is required, go for a GUI.
|
Powerwise: Is it better to use console or windows GUI application in C#(.NET)?
|
[
"",
"c#",
"windows",
"user-interface",
"console",
""
] |
I am trying to call out to a legacy dll compiled from FORTRAN code. I am new to Interop, but I've read some articles on it and it seems like my case should be fairly straightforward.
The method I really want to call has a complex method signature, but I can't even call this simple GetVersion method without getting a protected memory violation.
Here's my DllImport code:
```
[DllImport("GeoConvert.dll",
EntryPoint="_get_version@4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
ref string version);
```
Here's the FORTRAN code:
```
SUBROUTINE GetVer( VRSION )
C
!MS$DEFINE MSDLL
!MS$IF DEFINED (MSDLL)
ENTRY Get_Version (VRSION)
!MS$ATTRIBUTES DLLEXPORT,STDCALL :: Get_Version
!MS$ATTRIBUTES REFERENCE :: VRSION
!MS$ENDIF
!MS$UNDEFINE MSDLL
C
CHARACTER*8 VRSION
C
VRSION = '1.0a_FhC'
C
RETURN
END
```
Here's my unit test that fails:
```
[Test]
public void TestGetVersion()
{
string version = "";
LatLonUtils.GetGeoConvertVersion(ref version);
StringAssert.IsNonEmpty(version);
}
```
Here's the error message I get:
```
System.AccessViolationException
Message: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
```
Other things I've tried:
* Using the default marshalling
* Passing a char[] instead of a string (get method signature errors instead)
|
OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:
```
[DllImport("GeoConvert.dll",
EntryPoint="_get_version@4",
CallingConvention=CallingConvention.StdCall)]
public static extern void GetGeoConvertVersion([MarshalAs(UnmanagedType.LPArray)]
byte[] version);
```
With this test:
```
[Test]
public void TestGetVersion()
{
//string version = "";
byte[] version = new byte[8];
LatLonUtils.GetGeoConvertVersion(version);
char[] versionChars = System.Text.Encoding.ASCII.GetChars(version);
string versionString = new string(versionChars);
}
```
|
...snip...
OK, I got it to work, the problem was passing by ref. I'm not sure why, but this works:
...snip...
You need to pass by reference because that is the semantic being used by the FORTRAN code. The client code is passing in a buffer that the FORTRAN code is going to write to in lieu of using a return value.
...snip...
!MS$ATTRIBUTES REFERENCE :: VRSION
...snip...
This attribute in your FORTRAN code specifies that this parameter is passed by reference. That means the FORTRAN code is going to write to this address. If the DllImport doesn't declare it as a ref value also, you will get an access violation.
|
Protected Memory Violation calling FORTRAN DLL from C#
|
[
"",
"c#",
".net",
"interop",
"fortran",
"dllimport",
""
] |
My colleague insists on explicitly specifying the namespace in code as opposed to using the [using directive](http://msdn.microsoft.com/en-us/library/sf0df423.aspx). In other words he wants to use the fully qualified name for each type every time this type occurs in code. Something like
```
public class MyClass
{
public static void Main()
{
System.Console.WriteLine("Foo");
}
}
```
instead of:
```
using System;
public class MyClass
{
public static void Main()
{
Console.WriteLine("Foo");
}
}
```
You can imagine the consequences.
The pros he gives:
1. It's simpler to copy and paste code into other source files.
2. It is more readable (you see the namespaces right away).
My cons:
1. I have to write more
2. The code is less readable (I guess de gustibus non disputandum est)
3. No one does it!
What do you think about this?
|
For a slightly different answer: LINQ.
Extension methods are obtained only via "using" statements. So either the query syntax or the fluent interface will *only* work with the right "using" statements.
Even without LINQ, I'd say use "using"... reasoning that the more you can understand in fewer characters, the better. Some namespaces are very deep, but add no value to your code.
There are other extension methods too (not just LINQ) that would suffer the same; sure, you can use the static class, but the fluent interface is more expressive.
|
If you need to copy and paste code around so much as to actually benefit of having fully qualified types, you've got bigger problems.
Also, do you plan on remembering which namespace every single class is in in order to be able to type it fully qualified?
|
Should I agree to ban the "using" directive from my C# projects?
|
[
"",
"c#",
".net",
""
] |
I want to find a sql command or something that can do this where I have a table named tblFoo and I want to name it tblFooBar. However, I want the primary key to also be change, for example, currently it is:
```
CONSTRAINT [PK_tblFoo] PRIMARY KEY CLUSTERED
```
And I want a name change to change it to:
```
CONSTRAINT [PK_tblFooBar] PRIMARY KEY CLUSTERED
```
Then, recursively go through and cascade this change on all tables that have a foreigh key relationship, eg. from this:
```
CHECK ADD CONSTRAINT [FK_tblContent_tblFoo] FOREIGN KEY([fooID])
```
To this:
```
CHECK ADD CONSTRAINT [FK_tblContent_tblFooBar] FOREIGN KEY([fooID])
```
Naturally, I am trying not to go through and do this all manually because a) it is an error prone process, and b)it doesn't scale.
|
This is just off the top of my head and isn't complete (you'd need to add similar code for indexes). Also, you would need to either add code to avoid renaming objects from a table with the same base name, but additional characters - for example, this code would also list tblFoo2 and all of its associated objects. Hopefully it's a start for you though.
```
DECLARE
@old_name VARCHAR(100),
@new_name VARCHAR(100)
SET @old_name = 'tblFoo'
SET @new_name = 'tblFooBar'
SELECT
'EXEC sp_rename ''' + name + ''', ''' + REPLACE(name, @old_name, @new_name) + ''''
FROM dbo.sysobjects
WHERE name LIKE '%' + @old_name + '%'
```
|
Good answer by Tom
I've just extended his query here to include indexes
```
declare
@old nvarchar(100),
@new nvarchar(100)
set @old = 'OldName'
set @new = 'NewName'
select 'EXEC sp_rename ''' + name + ''', ''' +
REPLACE(name, @old, @new) + ''''
from sys.objects
where name like '%' + @old + '%'
union -- index renames
select 'EXEC sp_rename ''' + (sys.objects.name + '.' + sys.indexes.name) + ''', ''' +
REPLACE(sys.indexes.name, @old, @new) + ''', ''INDEX'''
from sys.objects
left join sys.indexes on sys.objects.object_id = sys.indexes.object_id
where sys.indexes.name like '%' + @old + '%'
```
|
Renaming Tables SQL Server, cascading that change through PK and FK's
|
[
"",
"sql",
"sql-server",
"t-sql",
"rename",
""
] |
In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as `(void*)0`. You could not assign NULL to any pointer other than `void*`, which made it kind of useless. Back in those days, it was accepted that you used `0` (zero) for null pointers.
To this day, I have continued to use zero as a null pointer but those around me insist on using `NULL`. I personally do not see any benefit to giving a name (`NULL`) to an existing value - and since I also like to test pointers as truth values:
```
if (p && !q)
do_something();
```
then using zero makes more sense (as in if you use `NULL`, you cannot logically use `p && !q` - you need to explicitly compare against `NULL`, unless you assume `NULL` is zero, in which case why use `NULL`).
Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?
Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.
|
Here's Stroustrup's take on this: [C++ Style and Technique FAQ](http://www.stroustrup.com/bs_faq2.html#null)
> In C++, the definition of `NULL` is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with `NULL` is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, `NULL` was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
>
> If you have to name the null pointer, call it `nullptr`; that's what it's called in C++11. Then, `nullptr` will be a keyword.
That said, don't sweat the small stuff.
|
There are a few arguments (one of which is relatively recent) which I believe contradict Bjarne's position on this.
1. **Documentation of intent**
Using `NULL` allows for searches on its use and it also highlights that the developer **wanted** to use a `NULL` pointer, irrespective of whether it is being interpreted by the compiler as `NULL` or not.
2. **Overload of pointer and 'int' is relatively rare**
The example that everybody quotes is:
```
void foo(int*);
void foo (int);
void bar() {
foo (NULL); // Calls 'foo(int)'
}
```
However, at least in my opinion, the problem with the above is not that we're using `NULL` for the null pointer constant: it's that we have overloads of `foo()` which take very different kinds of arguments. The parameter must be an `int` too, as any other type will result in an ambiguous call and so generate a helpful compiler warning.
3. **Analysis tools can help TODAY!**
Even in the absence of C++0x, there are tools available today that verify that `NULL` is being used for pointers, and that `0` is being used for integral types.
4. **[C++ 11](http://en.wikipedia.org/wiki/C++11) will have a new `std::nullptr_t` type.**
This is the newest argument to the table. The problem of `0` and `NULL` is being actively addressed for C++0x, and you can guarantee that for every implementation that provides `NULL`, the very first thing that they will do is:
```
#define NULL nullptr
```
For those who use `NULL` rather than `0`, the change will be an improvement in type-safety with little or no effort - if anything it may also catch a few bugs where they've used `NULL` for `0`. For anybody using `0` today... well, hopefully they have a good knowledge of regular expressions...
|
Do you use NULL or 0 (zero) for pointers in C++?
|
[
"",
"c++",
"null",
""
] |
I'm building a Lifestreaming app that will involve pulling down lots of feeds for lots of users, and performing data-mining, and machine learning algorithms on the results. GAE's load balanced and scalable hosting sounds like a good fit for a system that could eventually be moving around a LOT of data, but it's lack of cron jobs is a nuisance. Would I be better off using Django on a co-loc and dealing with my own DB scaling?
|
While I can not answer your question directly, my experience of building [Microupdater](https://github.com/juvenn/microupdater) (a news aggregator collecting a few hundred feeds on AppEngine) may give you a little insight.
* Fetching feeds. Fetching lots of feeds by cron jobs (it was the only solution until SDK 1.2.5) is not efficient and scalable, which has lower limit on job frequency (say 1 min, so you could only fetch at most 60 feeds hourly). And with latest SDK 1.2.5, there is [XMPP API](http://drupal.org/project/xmpp), which I have not implemented yet. The best promising approach would be [PubSubHubbub](http://code.google.com/p/pubsubhubbub/), of which you offer an callback url and HubBub will notify you new entries in **real-time**. And there is an [demo implementation](http://pubsubhubbub.appspot.com/) on AppEngine, which you can play around.
* Parsing feeds. You may already know that parsing feeds is cpu-intensive. I use [Universal Feed Parser](http://www.feedparser.org/) by Mark Pilgrim, when parsing a large feed (say a public google reader topic), AppEngine may fail to process all entries. My dashboard have a lot of these CPU-limit warnings. But it may result in my incapability to optimize the code yet.
Totally said, AppEngine is not yet an ideal platform for lifestream app, but that may change in future.
|
It might change when they offer paid plans, but as it stands, App Engine is not good for CPU intensive apps. It is designed to scale to handle a large number of requests, not necessarily a large amount of calculation per request. I am running into this issue with fairly minor calculations, and I fear I may have to start looking elsewhere as my data set grows.
|
Is Google App Engine a worthy platform for a Lifestreaming app?
|
[
"",
"python",
"django",
"google-app-engine",
"web-applications",
""
] |
I have a table that holds only two columns - a ListID and PersonID. When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.
Ideally, I would like to call something simple like
```
UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson
```
However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made. How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)
EDIT: Multiple ListIDs are used. If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4.
|
```
--out with the bad
DELETE
FROM MailingListSubscription
WHERE PersonId = @SourcePerson
and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson)
--update the rest (good)
UPDATE MailingListSubscription
SET PersonId = @DestPerson
WHERE PersonId = @SourcePerson
```
|
I have to agree with David B here. Remove all the older stuff that shouldn't be there and then do your update.
|
Merging contacts in SQL table without creating duplicate entries
|
[
"",
"sql",
"t-sql",
"duplicate-data",
""
] |
Is there a way of programmatically determining a rough geographical position of a mobile phone using J2ME application, for example determining the current cell? This question especially applies to non-GPS enabled devices.
I am not looking for a set of geographical coordinates, but an ability for a user to define location specific software behaviours.
Solution for any hardware will be highly appreciated; however the more generic a solution is — the better. Many thanks!
|
If the device supports the [JSR 179](http://jcp.org/en/jsr/detail?id=179) location API, you can use this. Last time I looked into this hardly any devices supported it, but that was a few years back.
|
this is my first post one stackoverflow.
You can get the cellID (The id of the phone pole that the mobile is connected to) on a lot of phones thru **`System.getProperty(String arg)`**
Here i have an example that tries a few keys to see if a cellID can be found. I have tested this on a lot of SonyEricsson mobiles and it works fine, as long as it isn't a Symbian mobile like P1 and so on. If you search the net you probably could find a lot more keys to find cellID:s for motorola, samsung and so on.
```
try{
String[] cellIDTags = {"com.sonyericsson.net.cellid", "phone.cid", "Siemens.CID", "CellID"};
for(int i = 0; i < cellIDTags.length; i++){
cellID = System.getProperty(cellIDTags[i]);
if(cellID != null && cellID != ""){
location.setCellId(cellID);
break;
}
}
}catch(Exception e){
cellID = "";
}
```
|
Geographical position from Java mobile application?
|
[
"",
"java",
"java-me",
"mobile",
"gis",
"mobile-phones",
""
] |
Anyone have any idea how to get the value of "Language for Non-Unicode Programs" in Control Panel Regional Settings programmatically using c#?
Already tried CultureInfo, RegionInfo and getting the default encoding using the Encoding object, but I can only get the Standards and Formats value or the main code page.
|
[GetSystemDefaultLocaleName](https://msdn.microsoft.com/en-us/library/dd318122(v=vs.85).aspx) or [GetSystemDefaultLCID](https://msdn.microsoft.com/en-us/library/dd318121(v=vs.85).aspx) (and its [P/Invoke declaration](http://pinvoke.net/default.aspx/kernel32/GetSystemDefaultLCID.html))
|
The [NLS Terminology](https://msdn.microsoft.com/en-us/library/dd319088(v=vs.85).aspx#Language_for_Non-Unicode_Programs) page in *Internationalization for Windows Applications* has the answer:
> An ANSI application should check the language for non-Unicode programs setting during installation. It uses **[GetACP](https://msdn.microsoft.com/en-us/library/dd318070(v=vs.85).aspx)** or **[GetOEMCP](https://msdn.microsoft.com/en-us/library/dd318114(v=vs.85).aspx)** to retrieve the value. No function is supported to set the language for non-Unicode programs.
The `GetACP` function returns the ["ANSI code page"](https://en.wikipedia.org/wiki/Windows_code_page#ANSI_code_page) (e.g. 1252 for english), while `GetOEMCP` returns the "OEM code page" (the code page used in the console, 437 for english).
[Code Pages](https://msdn.microsoft.com/en-us/library/windows/desktop/dd317752(v=vs.85).aspx) has more information about code pages in Windows.
|
Getting Language for Non-Unicode Programs
|
[
"",
"c#",
""
] |
What is the most efficient way to write the old-school:
```
StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
foreach (string s in strings)
{
sb.Append(s + ", ");
}
sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();
```
...in LINQ?
|
**This answer shows usage of LINQ (`Aggregate`) as requested in the question and is not intended for everyday use. Because this does not use a `StringBuilder` it will have horrible performance for very long sequences. For regular code use `String.Join` as shown in the other [answer](https://stackoverflow.com/a/218419/477420)**
Use aggregate queries like this:
```
string[] words = { "one", "two", "three" };
var res = words.Aggregate(
"", // start with empty string to handle empty list case.
(current, next) => current + ", " + next);
Console.WriteLine(res);
```
This outputs:
```
, one, two, three
```
An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an [IEnumerable](http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) object.
Remember that aggregate queries are executed immediately.
More information - [MSDN: Aggregate Queries](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/aggregate-queries)
---
If you really want to use `Aggregate` use variant using `StringBuilder` proposed in comment by [CodeMonkeyKing](https://stackoverflow.com/users/78830/codemonkeyking) which would be about the same code as regular `String.Join` including good performance for large number of objects:
```
var res = words.Aggregate(
new StringBuilder(),
(current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
.ToString();
```
|
```
return string.Join(", ", strings.ToArray());
```
---
In .Net 4, there's a new [overload](http://msdn.microsoft.com/en-us/library/dd783876.aspx) for `string.Join` that accepts `IEnumerable<string>`. The code would then look like:
```
return string.Join(", ", strings);
```
|
Using LINQ to concatenate strings
|
[
"",
"c#",
"linq",
"string-concatenation",
""
] |
in my application (c# 3.5) there are various processes accessing a single xml file (read and write) very frequently. the code accessing the file is placed in an assembly referenced by quite a couple of other applications. for example a windows service might instanciate the MyFileReaderWriter class (locatied in the previously mentioned assembly) and use the read/write methods of this class.
i'm looking for the best/fastest way to read and create/append the file with the least amount of locking. caching the files data and flushing new content periodically is not an option, since the data is critical.
I forgot to mention that I currently use the XDocument (LInq2Xml infrastructure) for reading/writing the content to the file.
|
To start with, make sure that all access to the XML Document is done through a single instance.
Then put a lock mechanism (that wait for unlock) at the beginning of the function that access it and unlock it at the end.
|
If by writing you're only appending to the document, then try this
<http://msdn.microsoft.com/en-us/library/aa302289.aspx>
Basically your xml document is a shell with a start and end tag. Between the tags is an include reference, that references another file, this other file is the body of the xml document.
For write operations this is many times faster, because you don't have to load the xml file each time you write to it, and you don't write the entire file each time.
Using an XmlWriter class you can very easily append nodes to the end of the body file.
When others want to read the xml, they simply open the document, their xml parser "knows" to load and parse both files.
Hope this helps.
|
How to access a file with the least amount of locking
|
[
"",
"c#",
"file",
"locking",
"io",
""
] |
As a complete beginner with no programming experience, I am trying to find beautiful Python code to study and play with. Please answer by pointing to a website, a book or some software project.
I have the following criterias:
* complete code listings (working, hackable code)
* beautiful code (highly readable, simple but effective)
* instructional for the beginner (yes, hand-holding is needed)
I've tried learning how to program for too long now, never gotten to the point where the rubber hits the road. My main agenda is best spelled out by [Nat Friedman's "How to become a hacker](http://nat.org/blog/?p=773)".
I'm aware of O'Reilly's "Beautiful Code", but think of it as too advanced and confusing for a beginner.
|
Buy [Programming Collective Intelligence](https://rads.stackoverflow.com/amzn/click/com/0596529325). Great book of interesting AI algorithms based on mining data and all of the examples are in very easy to read Python.
The other great book is [Text Processing in Python](https://rads.stackoverflow.com/amzn/click/com/0321112547)
|
Read the Python libraries themselves. They're working, hackable, elegant, and instructional. Some is simple, some is complex.
Best of all, you got it when you downloaded Python itself. It's in your Python library directory. Nothing more to do except start poking around.
|
Beginner looking for beautiful and instructional Python code
|
[
"",
"python",
""
] |
I am trying to install PHP onto my development box (XP SP3 / IIS 5.1) I've got PHP 5.2.6 stable downloaded (the MSI installer package) and I am getting an error "Cannot find httpd.conf". After that the install seems to breeze by quickly (more quickly than I would have expected) and when I try to execute a simple PHP script from my localhost test directory that I created, I get a slew of missing DLL errors. I have seen posts out there which indicate that its possible and has been done. I dont see any bug reports for this MSI at PHP.NET support. Any ideas?
|
Not sure if you already have this but I use WAMP from <http://www.wampserver.com/en>
It's easy and simple to set up, it has an icon in the system tray to show that its active and you can make it go online or available to the outside by clicking the icon and setting it. I used this when I was first learning PHP since it has everything in one, no need to setup any other service like IIS.
|
Probably the installer didn't configure your server to use PHP properly. Check out Microsoft's page on [enabling PHP on IIS](http://www.iis.net/php) or alternatively switch to Apache if that's a viable option.
|
Install PHP on XP / IIS 5.1?
|
[
"",
"php",
"windows-xp",
"installation",
"windows-installer",
""
] |
On our site, we get a large amount of photos uploaded from various sources.
In order to keep the file sizes down, we strip all [exif data](http://en.wikipedia.org/wiki/Exif) from the source using [mogrify](http://www.imagemagick.org/www/mogrify.html):
```
mogrify -strip image.jpg
```
What we'd like to be able to do is to insert some basic exif data (Copyright Initrode, etc) back onto this new "clean" image, but I can't seem to find anything in the docs that would achieve this.
Has anybody any experience of doing this?
If it can't be done through imagemagick, a PHP-based solution would be the next best thing!
Thanks.
|
You can save a large amount of space, especially if you have a large number of images..
Add the following to text.txt (format of the IPTC tags taken from [here](http://www.narf.ssji.net/~shtrom/wiki/tips/imagemanipulation)):
```
2#110#Credit="My Company"
2#05#Object Name="THE_OBJECT_NAME"
2#55#Date Created="2011-02-03 12:45"
2#80#By-line="BY-LINE?"
2#110#Credit="The CREDIT"
2#115#Source="SOURCE"
2#116#Copyright Notice="THE COPYRIGHT"
2#118#Contact="THE CONTACT"
2#120#Caption="AKA Title"
```
Strip all existing exif data from the image
```
mogrify -strip image.jpg
```
Add the credit to your image
```
mogrify -profile 8BIMTEXT:text.txt image.jpg
```
|
[Exiftool](http://www.sno.phy.queensu.ca/~phil/exiftool/) looks like it would be an exact match for you.
I haven't tried it but I'm now tempted to go and fix all my honeymoon photos which are marked 01/01/2074 because I forgot to reset the date after the batteries died.
|
How do I add exif data to an image?
|
[
"",
"php",
"image-processing",
"imagemagick",
"exif",
""
] |
How do I go about setting a `<div>` in the center of the screen using jQuery?
|
I like adding functions to jQuery so this function would help:
```
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
```
Now we can just write:
```
$(element).center();
```
Demo: [Fiddle](http://jsfiddle.net/DerekL/GbDw9/) (with added parameter)
|
I put a [jquery plugin](http://plugins.jquery.com/project/autocenter) here
VERY SHORT VERSION
```
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
```
SHORT VERSION
```
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
```
Activated by this code :
```
$('#mainDiv').center();
```
PLUGIN VERSION
```
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
```
Activated by this code :
```
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
```
is that right ?
# UPDATE :
From [CSS-Tricks](http://css-tricks.com/centering-percentage-widthheight-elements/)
```
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* Yep! */
width: 48%;
height: 59%;
}
```
|
Using jQuery to center a DIV on the screen
|
[
"",
"javascript",
"jquery",
"html",
"css",
"layout",
""
] |
How to copy file(s) from one solaris 9 machine to another solaris 9 machine using only java?
We have ssh access to both machines. The java program will run on one of those two machines.
Update: rsync is not really an option. can't install it easily (UNIX team is, hum, hard to deal with)
|
use the ssh library jsch -- <http://www.jcraft.com/jsch/>. This program is used by ant to do ssh transfers. very good -- been there a long time(> 5 years), decent documentation.
|
You could use Runtime.exec() to launch [rsync](http://samba.anu.edu.au/rsync/).
|
copy files from one solaris 9 to another using java
|
[
"",
"java",
"ssh",
""
] |
Could somebody please point me in the right direction for learning how to do networking in C#/.net 3.5? Code samples and explanations are welcome. Basically I am looking for how to do asynchronous/multithreaded server/client models.
I am fairly comfortable with the basics in how to accomplish this in C++ with WinSock but though all of my research cannot seem to grasp this concept in C#.
Thanks for any assistance you can provide :)
|
If WCF meets your needs, it's worth looking at. [ZeroC](http://www.zeroc.com) and other alternative higher level libraries exist. Otherwise there are several different ways to work closer to the socket level if that's what you need.
### TcpClient/UdpClient
These provide a relatively thin wrapper around the underlying sockets. It essentially provides a Stream over the socket. You can use the async methods on the NetworkStream (BeginRead, etc.). I don't like this one as the wrapper doesn't provide that much and it tends to be a little more awkward than using the socket directly.
### Socket - Select
This provides the classic Select technique for multiplexing multiple socket IO onto a single thread. Not recommended any longer.
### Socket - APM Style
The Asynchronous Programming Model (AKA IAsyncResult, Begin/End Style) for sockets is the primary technique for using sockets asynchronously. And there are several variants. Essentially, you call an async method (e.g., BeginReceive) and do one of the following:
1. Poll for completion on the returned IAsyncResult (hardly used).
2. Use the WaitHandle from the IAsyncResult to wait for the method to complete.
3. Pass the BeginXXX method a callback method that will be executed when the method completes.
The best way is #3 as it is the usually the most convenient. When in doubt, use this method.
Some links:
* [MSDN Magazine Article on Sockets](http://msdn.microsoft.com/en-us/magazine/cc300760.aspx)
* [A Jeffery Richter Article on the Asynchronous Programming Model](http://msdn.microsoft.com/en-us/magazine/cc163467.aspx)
### .NET 3.5 High Performance Sockets
.NET 3.5 introduced a new model for async sockets that uses events. It uses the "simplified" async model (e.g., Socket.SendAsync). Instead of giving a callback, you subscribe to an event for completion and instead of an IAsyncResult, you get SocketAsyncEventArgs. The idea is that you can reuse the SocketAsyncEventArgs and pre-allocate memory for socket IO. In high performance scenarios this can be much more efficient that using the APM style. In addition, if you do pre-allocate the memory, you get a stable memory footprint, reduced garbage collection, memory holes from pinning etc. Note that worrying about this should only be a consideration in the most high performance scenarios.
* [MSDN Magazine: Get Connected With The .NET Framework 3.5](http://msdn.microsoft.com/en-us/magazine/cc163356.aspx)
* [MSDN Information with technique for pre-allocating memory](http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx)
### Summary
For most cases use the callback method of the APM style unless you prefer the style of the SocketAsyncEventArgs / Async method. If you've used CompletionPorts in WinSock, you should know that both of these methods use CompletionPorts under the hood.
|
In .NET 3.5 world you should definitely learn [Windows Communication Foundation](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) - .NET framework for networking.
Useful link:
[Synchronous and Asynchronous Operations (in WCF)](http://msdn.microsoft.com/en-us/library/ms734701.aspx)
You can find useful WCF information on StackOverflow browsing posts [tagged with WCF](https://stackoverflow.com/questions/tagged/wcf) tag
|
networking in .net/C#
|
[
"",
"c#",
".net",
"networking",
"asynchronous",
""
] |
Does anyone know if it is possible to reliably determine (programattically C/C++...) whether or not a firewall or IP filtering software is installed on a Windows PC? I need to detect whether a certain server IP is being blocked in my client software by the host OS.
I don't need to worry about external hardware firewals in this situation as I have full control of this. It is only software firewalls that I am concerned with. My hope was that I could iterate the windows network stack or NDIS interfaces and determine this
|
After reading some of your comments in reply to other answers, I think this might actually be closer to what you're looking for. It might not catch every type of firewall but any major firewall vendor should be registered with the Security Center and therefore detected with this method. You could also combine this with some of the other answers here to give yourself a second level of verification.
### [Detecting running firewalls in windows](http://www.experts-exchange.com/Programming/Languages/CPP/Q_21645145.html)
It's an Expert's Exchange post so you may not be able to read the thread. Just in case, I've copied and pasted the relevant info. It's in VBScript but it should point you in the right direction as far as what WMI namespaces you can use.
> **KemalRouge**: I've just solved this problem with some help from a
> colleague. He pointed me in the direction of a knowledge base article,
> which pointed out that this information was stored in the WMI database
>
> Basically, it's possible to query the WMI in a few lines of code to
> find out what firewalls/anti-virus software is being monitored by the
> Security Center, and the status of this software (i.e. enabled or not).
>
> Anyway, if you're interested, here's some VB code I used to test this out
> (you'll need a reference to "Microsoft WMI Scripting V1.2 Library"):
```
Private Sub DumpFirewallInfo()
Dim oLocator As WbemScripting.SWbemLocator
Dim oService As WbemScripting.SWbemServicesEx
Dim oFirewalls As WbemScripting.SWbemObjectSet
Dim oFirewall As WbemScripting.SWbemObjectEx
Dim oFwMgr As Variant
Set oFwMgr = CreateObject("HNetCfg.FwMgr")
Debug.Print "Checking the Windows Firewall..."
Debug.Print "Windows Firewal Enabled: " & oFwMgr.LocalPolicy.CurrentProfile.FirewallEnabled
Debug.Print ""
Set oFwMgr = Nothing
Debug.Print "Checking for other installed firewalls..."
Set oLocator = New WbemScripting.SWbemLocator
Set oService = oLocator.ConnectServer(".", "root\SecurityCenter")
oService.Security_.ImpersonationLevel = 3
Set oFirewalls = oService.ExecQuery("SELECT * FROM FirewallProduct") ' This could also be "AntivirusProduct"
For Each oFirewall In oFirewalls
Debug.Print "Company: " & vbTab & oFirewall.CompanyName
Debug.Print "Firewall Name: " & vbTab & oFirewall.DisplayName
Debug.Print "Enabled: " & vbTab & Format$(oFirewall.Enabled)
Debug.Print "Version: " & vbTab & oFirewall.versionNumber
Debug.Print ""
Next oFirewall
Set oFirewall = Nothing
Set oFirewalls = Nothing
Set oService = Nothing
Set oLocator = Nothing
End Sub
```
|
There could be a hack if you can assume following:
1. Outgoing HTTP connections are allowed
2. You can run one of your own service on another server listening on port 80
Code your service to accept an IP [and a port or maybe a url]. It must return whether it was able to connect to the IP.
This way you can find out whether the actual server is up and running. If the server is not available directly you can conclude that it is being blocked by a firewall.
If you do not want to code/run your own service, you might be able to use one of the network status web-service available on the internet.
|
Determine if IP is blocked
|
[
"",
"c++",
"windows",
"security",
"networking",
""
] |
I'm trying to get a query working that takes the values (sometimes just the first part of a string) from a form control. The problem I have is that it only returns records when the full string is typed in.
i.e. in the surname box, I should be able to type gr, and it brings up
green
grey
graham
but at present it's not bringing up anything uless the full search string is used.
There are 4 search controls on the form in question, and they are only used in the query if the box is filled in.
The query is :
```
SELECT TabCustomers.*,
TabCustomers.CustomerForname AS NameSearch,
TabCustomers.CustomerSurname AS SurnameSearch,
TabCustomers.CustomerDOB AS DOBSearch,
TabCustomers.CustomerID AS MemberSearch
FROM TabCustomers
WHERE IIf([Forms]![FrmSearchCustomer]![SearchMember] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchMember]=[customerid])=True
AND IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchFore] Like [customerforname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![SearchLast] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchLast] Like [customersurname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![Searchdate] Is Null
,True
,[Forms]![FrmSearchCustomer]![Searchdate] Like [customerDOB] & "*")=True;
```
|
## There is an Access Method for that!
If you have your "filter" controls on the form, why don't you use the Application.buildCriteria method, that will allow you to add your filtering criterias to a string, then make a filter out of this string, and build your WHERE clause on the fly?
```
selectClause = "SELECT TabCustomers.* FROM TabCustomers"
if not isnull(Forms!FrmSearchCustomer!SearchMember) then
whereClause = whereClause & application.buildCriteria(your field name, your field type, your control value) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchFore) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchLast) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchDate) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
--get rid of the last "AND"
if len(whereClause) > 0 then
whereClause = left(whereClause,len(whereClause)-5)
selectClause = selectClause & " WHERE " & whereClause
endif
-- your SELECT instruction is ready ...
```
EDIT: the buildCriteria will return (for example):
* `'field1 = "GR"'` when you type "GR" in the control
* `'field1 LIKE "GR*"'` when you type `"GR*"` in the control
* `'field1 LIKE "GR*" or field1 like "BR*"'` if you type `'LIKE "GR*" OR LIKE "BR*"'` in the control
PS: if your "filter" controls on your form always have the same syntax (let's say "search\_fieldName", where "fieldName" corresponds to the field in the underlying recordset) and are always located in the same zone (let's say formHeader), it is then possible to write a function that will automatically generate a filter for the current form. This filter can then be set as the form filter, or used for something else:
```
For each ctl in myForm.section(acHeader).controls
if ctl.name like "search_"
fld = myForm.recordset.fields(mid(ctl.name,8))
if not isnull(ctl.value) then
whereClause = whereClause & buildCriteria(fld.name ,fld.type, ctl.value) & " AND "
endif
endif
next ctl
if len(whereClause)> 0 then ...
```
|
You have your LIKE expression backwards. I have rewritten the query to remove the unnecessary IIF commands and to fix your order of operands for the LIKE operator:
```
SELECT TabCustomers.*
FROM TabCustomers
WHERE (Forms!FrmSearchCustomer!SearchMember Is Null Or Forms!FrmSearchCustomer!SearchMember=[customerid])
And (Forms!FrmSearchCustomer.SearchFore Is Null Or [customerforname] Like Forms!FrmSearchCustomer!SearchFore & "*")
And (Forms!FrmSearchCustomer!SearchLast Is Null Or [customersurname] Like Forms!FrmSearchCustomer!SearchLast & "*")
And (Forms!FrmSearchCustomer!Searchdate Is Null Or [customerDOB] Like Forms!FrmSearchCustomer!Searchdate & "*");
```
I built that query by replicating the most likely circumstance: I created a dummy table with the fields mentioned and a form with the fields and a subform with the query listed above being refreshed when the search button was pushed. I can provide a download link to the example I created if you would like. The example works as expected. J only picks up both Jim and John, while John or Jo only pulls the John record.
|
Returning records that partially match a value
|
[
"",
"sql",
"ms-access",
"sql-like",
""
] |
I have derived a TabControl with the express purpose of enabling double buffering, except nothing is working as expected. Here is the TabControl code:
```
class DoubleBufferedTabControl : TabControl
{
public DoubleBufferedTabControl() : base()
{
this.DoubleBuffered = true;
this.SetStyle
(
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor,
false
);
}
}
```
This Tabcontrol is then set with it's draw mode as 'OwnerDrawnFixed' so i can changed the colours. Here is the custom drawing method:
```
private void Navigation_PageContent_DrawItem(object sender, DrawItemEventArgs e)
{
//Structure.
Graphics g = e.Graphics;
TabControl t = (TabControl)sender;
TabPage CurrentPage = t.TabPages[e.Index];
//Get the current tab
Rectangle CurrentTabRect = t.GetTabRect(e.Index);
//Get the last tab.
Rectangle LastTab = t.GetTabRect(t.TabPages.Count - 1);
//Main background rectangle.
Rectangle BackgroundRect = new Rectangle(LastTab.Width, t.Bounds.Y - 4, t.Width - (LastTab.Width), t.Height);
//Tab background rectangle.
Rectangle TabBackgroundRect = new Rectangle(0, LastTab.Y + LastTab.Height, LastTab.Width, t.Bounds.Height - (LastTab.Y + LastTab.Height));
//Set anitialiasing for the text.
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
//String format for the text.
StringFormat StringFormat = new StringFormat();
StringFormat.Alignment = StringAlignment.Center;
StringFormat.LineAlignment = StringAlignment.Center;
//Fill the background.
g.FillRectangle(Brushes.LightGray, BackgroundRect);
g.FillRectangle(Brushes.Bisque, TabBackgroundRect);
//Draw the selected tab.
if(e.State == DrawItemState.Selected)
{
g.FillRectangle(Brushes.White, e.Bounds);
Rectangle SelectedTabOutline = new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, e.Bounds.Width, e.Bounds.Height - 4);
g.DrawRectangle(new Pen(Brushes.LightGray, 4f), SelectedTabOutline);
g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Bold, GraphicsUnit.Point), new SolidBrush(Color.FromArgb(70, 70, 70)), CurrentTabRect, StringFormat);
}
else
{
g.FillRectangle(new SolidBrush(Color.FromArgb(230, 230, 230)), e.Bounds);
g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Regular, GraphicsUnit.Point), Brushes.Gray, CurrentTabRect, StringFormat);
}
}
```
All to no avail however, as this control is not double buffered and still flickers when resized.
**Any ideas?**
|
If you read the documentation, it says, "This member is not meaningful for this control." If you want the control to be drawn utilizing double-buffering, you'll have to implement it yourself. Besides the fact that if you owner-draw the control, you would have to implement double-buffering yourself anyhow.
|
First of all, you can get rid of your `TabControl` code—you turn on buffering, and then immediately turn it off, so it's not actually doing anything useful.
Part of your problem is that you're trying to paint just *part* of the `TabControl`.
The easiest solution that gives about a 90% solution (it's still possible to get a flicker) is to add this to your form class:
```
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}
```
If you want to be *very* sure of getting no flicker, you'll need to draw the entire `TabControl` yourself, and make sure to ignore background painting requests.
Edit: Note that this will only work in XP and later.
|
Double buffering problem of a derived owner-drawn TabControl?
|
[
"",
"c#",
"tabcontrol",
"doublebuffered",
"ownerdrawn",
""
] |
I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?
|
Check the `AUTH_USER` request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user.
In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and `AUTH_USER` will be `MYDOMAIN\user.name` without the users having to explicitly log in to your web app.
|
I've got php mysql running on IIS - I can use `$_SERVER["AUTH_USER"]` *if* I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important)
I've used this to get my user and domain:
```
$user = $_SERVER['AUTH_USER'];
```
`$user` will return a value like: `DOMAIN\username` on our network, and then it's just a case of removing the `DOMAIN\` from the string.
This has worked in IE, FF, Chrome, Safari (tested) so far.
|
Can you get a Windows (AD) username in PHP?
|
[
"",
"php",
"windows",
"authentication",
""
] |
In Python, I want to make **selected** instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)
|
You should use the `@property` decorator.
```
>>> class a(object):
... def __init__(self, x):
... self.x = x
... @property
... def xval(self):
... return self.x
...
>>> b = a(5)
>>> b.xval
5
>>> b.xval = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
```
|
Here's how:
```
class whatever(object):
def __init__(self, a, b, c, ...):
self.__foobar = 1
self.__blahblah = 2
foobar = property(lambda self: self.__foobar)
blahblah = property(lambda self: self.__blahblah)
```
(Assuming `foobar` and `blahblah` are the attributes you want to be read-only.) Prepending **two** underscores to an attribute name effectively hides it from outside the class, so the internal versions won't be accessible from the outside. This **only works for new-style classes inheriting from object** since it depends on `property`.
On the other hand... this is a pretty silly thing to do. Keeping variables private seems to be an obsession that comes from C++ and Java. Your users should use the public interface to your class because it's well-designed, not because you force them to.
Edit: Looks like Kevin already posted a similar version.
|
What is the easiest, most concise way to make selected attributes in an instance be readonly?
|
[
"",
"python",
"attributes",
"readonly",
""
] |
Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like
```
FindAllPostByTags(IList<Tag> tags)
```
that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!
|
You could also just use an `IN` statement
```
DetachedCriteria query = DetachedCriteria.For<Post>();
query.CreateCriteria("Post").Add(Expression.In("TagName", string.Join(",",tags.ToArray()) );
```
I haven't compiled that so it could have errors
|
I don't have a system at hand with a Castle install right now, so I didn't test or compile this, but the code below should about do what you want.
```
Junction c = Expression.Conjunction();
foreach(Tag t in tags)
c = c.Add( Expression.Eq("Tag", t);
return sess.CreateCriteria(typeof(Post)).Add(c).List();
```
|
C# + Castle ActiveRecord: HasAndBelongsToMany and collections
|
[
"",
"c#",
".net",
"nhibernate",
"hql",
"castle-activerecord",
""
] |
I recently wrote a DLL in C# (.Net 2.0) which contains a class that requires an IP address. A co-worker of mine altered the class to retrieve the IP from a ".dll.config" (XML) file -- This apparently is automatically generated by the "Application Settings" file he created (Settings1.settings). The benefit of this was to allow the end-user to change the IP address in the XML/config file at will.
Unfortunately, when I check his code out of the tree and try to compile (or use) this new code, any application calling this DLL only gets the default value, rather than the value from the file.
The constructor that calls the config file looks like this:
```
public class form : System.Windows.Forms.Form
{
public form()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
IP = IPAddress.Parse(Settings1.Default.IPAddress);
}
}
```
I found [a reference to this problem on the MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/clr/thread/f3a4b138-6e6c-42e3-86e8-1f86c90f8fb4/) where a user said:
> the 'old' values (the ones you define at development time) are hard coded. If the franework isn't able to access or open the config file it will use the defaults instead. This will always happen if you use settings in a dll.
1. Does this mean that I cannot store an external value for a DLL in a config file? (My co-worker has somehow made this work...)
2. Since my framework appears to be unable to access or open the config file, how do I figure out why it's failing? Or even detect when this happens?
**Decker**: That helps a bit. Unfortunately, I am writing this DLL to a specification, so I don't actually have access to the Application's config file. As you'll note above, my co-worker created a "Settings**1**.settings" file. I didn't understand this at the time, but it seems now that adding the "1" keeps it out of the settings space of any application that calls it.
I guess what I'm trying to figure out is why the DLL doesn't seem to find the config file sitting next to it in the same directory. Tracing thru the code step-by-step reveals nothing.
As an aside, I can change the "Output Type" of my assembly from "Class Library" to "Windows Application" and add the following lines at the beginning of my DLL code:
```
[STAThread]
public static void Main(string[] args)
{
System.Windows.Forms.Application.Run(new form());
}
```
When I run this, it generates a different config file (a ".exe.config") and that one I can alter and have it pull the new data from the file. So I'm a bit confused. Any ideas?
|
I'm addressing this exact issue in an application I'm in the midst of prototyping. Although Decker's suggestion of hacking the config files together should work I think this is a pretty inconvenient manual hack to perform as part of a build cycle. Instead of that I've decided that the cleanest solution is to just have each library parse its own library.dll.config file. Its still not perfect and it requires some extra boiler-plate code, but it seems to be the only way to get around the byzantine way that .Net handles these app.config files.
|
I use this technique all time time. Often I have a library assembly that requires certain settings, and I need them set both by testing projects as well as the primary "executable" assemblies -- be they web projects or Windows service projects.
You're correct in that when you create a settings file for any project, it adds an application config file. The value you enter for any setting is stored in two places -- the config file AND in attributes on the classes created by the settings infrastructure. When a config file is not found, the values embedded in the attributes are used.
Here is a snippet that shows such an attribute:
Here is a snippet that shows the default value of the ConcordanceServicesEndpointName in the generated class:
```
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("InternalTCP")]
public string ConcordanceServicesEndpointName {
get {
return ((string)(this["ConcordanceServicesEndpointName"]));
}
}
```
What you want to do is copy the configuration section out of the app.config file from the library assembly project and merge it (carefully) into the applicable web.config or app.config for the main assembly. At runtime, that's the only config file that is used.
Here is an example:
```
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="LitigationPortal.Documents.BLL.DocumentsBLLSettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<LitigationPortal.Documents.BLL.DocumentsBLLSettings>
<setting name="ConcordanceServicesEndpointName" serializeAs="String">
<value>InternalTCP</value>
</setting>
</KayeScholer.LitigationPortal.Documents.BLL.DocumentsBLLSettings>
</applicationSettings>
```
You should copy these sections into the "true" config file.
|
Settings.Default.<property> always returns default value instead of value in persistant storage (XML file)
|
[
"",
"c#",
".net",
"dll",
"application-settings",
""
] |
```
foreach($arrayOne as $value){
do function
}
```
In the above example, I'd like to pass $arrayOne into a loop, have a function operate that removes some elements of $arrayOne and then have the loop pass over the reduced $arrayOne on the elements that are left until the loop returns false.
Recommendations?
|
If you want to make modifications to the value of array items, use by reference. If you want to entirely remove array items, split out the key / value pairs.
```
$arrayOne = array('example', 'listing of', 'stuff');
foreach ($arrayOne as $key => &$value) {
$value .= ' alteration';
if ($value == 'listing of alteration') {
unset($arrayOne[ $key ]);
}
}
```
The above code will add the text " alteration" to the end of each item in the array.
It will also remove the second index when it matches "listing of alteration". Tested on PHP 5.2
|
Do you just need a function to remove some elements of an array?
If so, you can use [array\_filter](http://uk.php.net/array_filter).
|
Replacing array in foreach loop with array modified in same loop
|
[
"",
"php",
"loops",
""
] |
I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.
When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)
I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage.
So, boiled down, the question is:
Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.
|
Sounds like a job for XMLUnit
* <http://www.xmlunit.org/>
* <https://github.com/xmlunit>
Example:
```
public class SomeTest extends XMLTestCase {
@Test
public void test() {
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences
// can also compare xml Documents, InputSources, Readers, Diffs
assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase
}
}
```
|
The following will check if the documents are equal using standard JDK libraries.
```
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc1 = db.parse(new File("file1.xml"));
doc1.normalizeDocument();
Document doc2 = db.parse(new File("file2.xml"));
doc2.normalizeDocument();
Assert.assertTrue(doc1.isEqualNode(doc2));
```
normalize() is there to make sure there are no cycles (there technically wouldn't be any)
The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand `xml:space` if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.
|
Best way to compare 2 XML documents in Java
|
[
"",
"java",
"xml",
"testing",
"parsing",
"comparison",
""
] |
Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.
|
From <http://www.codeave.com/javascript/code.asp?u_log=7004>:
```
var input = document.getElementById('myTextInput');
input.focus();
input.select();
```
```
<input id="myTextInput" value="Hello world!" />
```
|
In your input tag, place the following:
```
onFocus="this.select()"
```
|
how to auto select an input field and the text in it on page load
|
[
"",
"javascript",
"html",
""
] |
I know you can just use CSS to hide the DIV or Silverlight Plugin, but is there a way to instantiate a Silverlight Component/App using JavaScript that doesn't show any UI element at all?
There is alot of great functionality in Silverlight, like MultiThreading and compiled code, that could be utilized by traditional Ajax apps without using the XAML/UI layer of Silverlight at all.
I would like to just use the standard HTML/CSS for my UI layer only, and use some compiled .NET/Silverlight code in the background.
|
Yes you can, and some of the reasons you make makes perfect sense. I did a talk on the HTML bridge at CodeCampNZ some weeks back, and have [a good collection of resources](http://jonas.follesoe.no/2008/09/01/unit-testing-presentation-model-and-the-html-bridge-at-codecamp-nz/) up on my blog.
I also recommend checking out [Wilco Bauwers blog for lots of detail](http://www.wilcob.com/Wilco/Silverlight/silverlight-interoperability.aspx) on the HTML bridge.
Some other scenarios for non visual Silverlight:
* Writing new code in a managed language (C#, Ruby, JScript.NET, whatever) instead of native (interpreted) JavaScript.
* Using OpenFileDialog to read files on the client, without round-tripping to the server.
* Storing transient data securely on the client in isolated storage.
* Improving responsiveness and performance by executing work in the background through a BackgroundWorker or by using ordinary threads.
* Accessing cross-domain data via the networking APIs.
* Retrieving real-time data from the server via sockets.
* Binding data by re-using WPF's data-binding engine.
|
Yes. I think this is particularly intriguing when mixed with [other dynamic languages](http://www.codeplex.com/sdlsdk) -- but then, I'm probably biased. :)
**Edit:** But you'd need to use the managed Javascript that's part of the Silverlight Dynamic Languages SDK and not the normal Javascript that's part of the browser.
|
Can you use Silverlight with AJAX without any UI element?
|
[
"",
"javascript",
"ajax",
"silverlight",
""
] |
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like `obj.attr` ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?
**Edit:**
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.
---
If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.
|
The generally accepted way of doing things is just using simple attributes, like so
```
>>> class MyClass:
... myAttribute = 0
...
>>> c = MyClass()
>>> c.myAttribute
0
>>> c.myAttribute = 1
>>> c.myAttribute
1
```
If you do find yourself needing to be able to write getters and setters, then what you want to look for is "python class properties" and [Ryan Tomayko's article on
Getters/Setters/Fuxors](http://tomayko.com/writings/getters-setters-fuxors) is a great place to start (albeit a little long)
|
With regards to the single and double-leading underscores: both indicate the same concept of 'privateness'. That is to say, people will know the attribute (be it a method or a 'normal' data attribute or anything else) is not part of the public API of the object. People will know that to touch it directly is to invite disaster.
On top of that, the double-leading underscore attributes (but not the single-leading underscore attributes) are *name-mangled* to make accessing them *by accident* from subclasses or anywhere else outside the current class less likely. You can still access them, but not as trivially. For example:
```
>>> class ClassA:
... def __init__(self):
... self._single = "Single"
... self.__double = "Double"
... def getSingle(self):
... return self._single
... def getDouble(self):
... return self.__double
...
>>> class ClassB(ClassA):
... def getSingle_B(self):
... return self._single
... def getDouble_B(self):
... return self.__double
...
>>> a = ClassA()
>>> b = ClassB()
```
You can now trivially access `a._single` and `b._single` and get the `_single` attribute created by `ClassA`:
```
>>> a._single, b._single
('Single', 'Single')
>>> a.getSingle(), b.getSingle(), b.getSingle_B()
('Single', 'Single', 'Single')
```
But trying to access the `__double` attribute on the `a` or `b` instance directly won't work:
```
>>> a.__double
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ClassA instance has no attribute '__double'
>>> b.__double
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ClassB instance has no attribute '__double'
```
And though methods defined in `ClassA` can get at it directly (when called on either instance):
```
>>> a.getDouble(), b.getDouble()
('Double', 'Double')
```
Methods defined on `ClassB` can not:
```
>>> b.getDouble_B()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in getDouble_B
AttributeError: ClassB instance has no attribute '_ClassB__double'
```
And right in that error you get a hint about what's happening. The `__double` attribute name, when accessed inside a class, is being name-mangled to include the name of the class that it is being accessed *in*. When `ClassA` tries to access `self.__double`, it actually turns -- at compiletime -- into an access of `self._ClassA__double`, and likewise for `ClassB`. (If a method in `ClassB` were to assign to `__double`, not included in the code for brevity, it would therefor not touch `ClassA`'s `__double` but create a new attribute.) There is no other protection of this attribute, so you can still access it directly if you know the right name:
```
>>> a._ClassA__double, b._ClassA__double
('Double', 'Double')
```
**So why is this a problem?**
Well, it's a problem any time you want to inherit and change the behaviour of any code dealing with this attribute. You either have to reimplement everything that touches this double-underscore attribute directly, or you have to guess at the class name and mangle the name manually. The problem gets worse when this double-underscore attribute is actually a method: overriding the method *or calling the method in a subclass* means doing the name-mangling manually, or reimplementing all the code that calls the method to not use the double-underscore name. Not to mention accessing the attribute dynamically, with `getattr()`: you will have to manually mangle there, too.
On the other hand, because the attribute is only trivially rewritten, it offers only superficial 'protection'. Any piece of code can still get at the attribute by manually mangling, although that will make *their* code dependant on the name of *your* class, and efforts on your side to refactor your code or rename your class (while still keeping the same user-visible name, a common practice in Python) would needlessly break their code. They can also 'trick' Python into doing the name-mangling for them by naming their class the same as yours: notice how there is no module name included in the mangled attribute name. And lastly, the double-underscore attribute is still visible in all attribute lists and all forms of introspection that don't take care to skip attributes starting with a (*single*) underscore.
So, *if* you use double-underscore names, use them exceedingly sparingly, as they can turn out quite inconvenient, and never use them for methods **or anything else a subclass may ever want to reimplement, override or access directly**. And realize that double-leading underscore name-mangling offers *no real protection*. In the end, using a single leading underscore wins you just as much and gives you less (potential, future) pain. Use a single leading underscore.
|
Python object attributes - methodology for access
|
[
"",
"python",
"oop",
"object",
"attributes",
""
] |
Just wondering what the difference between `BeginInvoke()` and `Invoke()` are?
Mainly what each one would be used for.
EDIT: What is the difference between creating a threading object and calling invoke on that and just calling `BeginInvoke()` on a delegate? or are they the same thing?
|
Do you mean `Delegate.Invoke`/`BeginInvoke` or `Control.Invoke`/`BeginInvoke`?
* `Delegate.Invoke`: Executes synchronously, on the same thread.
* `Delegate.BeginInvoke`: Executes asynchronously, on a `threadpool` thread.
* `Control.Invoke`: Executes on the UI thread, but calling thread waits for completion before continuing.
* `Control.BeginInvoke`: Executes on the UI thread, and calling thread doesn't wait for completion.
Tim's answer mentions when you might want to use `BeginInvoke` - although it was mostly geared towards `Delegate.BeginInvoke`, I suspect.
For Windows Forms apps, I would suggest that you should *usually* use `BeginInvoke`. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a `Person` with `FirstName` and `LastName` properties, and you did:
```
person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";
```
Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)
Unless you have this sort of issue, however, `Control.BeginInvoke` is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use `Control.BeginInvoke` in a "fire and forget" manner - i.e. without ever calling `EndInvoke`. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.
|
Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.
In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).
In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.
Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.
|
What's the difference between Invoke() and BeginInvoke()
|
[
"",
"c#",
".net",
"multithreading",
"invoke",
"begininvoke",
""
] |
The Mutex class is very misunderstood, and Global mutexes even more so.
What is good, safe pattern to use when creating Global mutexes?
One that will work
* Regardless of the locale my machine is in
* Is guaranteed to release the mutex properly
* Optionally does not hang forever if the mutex is not acquired
* Deals with cases where other processes abandon the mutex
|
I want to make sure this is out there, because it's so hard to get right:
```
using System.Runtime.InteropServices; //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid =
((GuidAttribute)Assembly.GetExecutingAssembly().
GetCustomAttributes(typeof(GuidAttribute), false).
GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );
// Need a place to store a return value in Mutex() constructor call
bool createdNew;
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule =
new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
, null)
, MutexRights.FullControl
, AccessControlType.Allow
);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact that the mutex was abandoned in another process,
// it will still get acquired
hasHandle = true;
}
// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statement
if(hasHandle)
mutex.ReleaseMutex();
}
}
}
```
|
Using the accepted answer I create a helper class so you could use it in a similar way you would use the Lock statement. Just thought I'd share.
Use:
```
using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
//Only 1 of these runs at a time
RunSomeStuff();
}
```
And the helper class:
```
class SingleGlobalInstance : IDisposable
{
//edit by user "jitbit" - renamed private fields to "_"
public bool _hasHandle = false;
Mutex _mutex;
private void InitMutex()
{
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
_mutex = new Mutex(false, mutexId);
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
_mutex.SetAccessControl(securitySettings);
}
public SingleGlobalInstance(int timeOut)
{
InitMutex();
try
{
if(timeOut < 0)
_hasHandle = _mutex.WaitOne(Timeout.Infinite, false);
else
_hasHandle = _mutex.WaitOne(timeOut, false);
if (_hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
}
catch (AbandonedMutexException)
{
_hasHandle = true;
}
}
public void Dispose()
{
if (_mutex != null)
{
if (_hasHandle)
_mutex.ReleaseMutex();
_mutex.Close();
}
}
}
```
|
What is a good pattern for using a Global Mutex in C#?
|
[
"",
"c#",
"concurrency",
"mutex",
""
] |
Is it possible to assign a custom ID to a HTTP session through Servlet API?
I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated.
And I looked at every documentation about session handling but nowhere I find what I need.
It's a requirement for a project, so if it's not possible, I need to know the reasons (or it's only not available through API?).
|
If you are using Tomcat, you may be able to create a custom session manager (see [this discussion](http://markmail.org/message/im3wkoeskkgjaphv#query:tomcat%20custom%20session%20Manager+page:1+mid:lgl2bdm26avvjx37+state:results)). You would then have access to the Tomcat [Session](http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/Session.html) object and could call setId.
|
The servlet API does not support creating your own cookie value. In fact, it does not guarantee that sessions are maintained via cookies... it specifically states that they can be maintained via a mechanism such as "URL Rewriting". It DOES guarantee that the session is maintained in some fashion, and that pretty much requires some sort of unique ID which is passed to the browser and returned, but no mechanism is provided in the Servlet API for servlet code to control what value is used. Nor do common servlet containers that I know of (such as Tomcat) provide a means for controlling this value.
However, none of this should be a problem for you if I understand your requirements properly. Just because Tomcat (or whatever servlet container you use) is creating a unique ID based on its own algorithms (that contain things like cryptographically secure random number generators to prevent "guessing" of session IDs), doesn't mean that you cannot create a SEPARATE ID which meets your requirements (based on user and time, unique across all sessions... whatever you need). This ID can be stored in the session (if that's all you need), or can be stored on the browser in a separate cookie (if you need it maintained across sessions). The only effect would be that the browser was storing TWO cookies -- and most websites store many more cookies than that!
|
Custom ID in session handling by Java Servlet API
|
[
"",
"java",
"session",
"web-applications",
"servlets",
""
] |
What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that.
|
This should do it:
```
[^\x00-\x7F]+
```
It matches any character which is not contained in the [ASCII character set](http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange) (0-127, i.e. 0x0 to 0x7F).
You can do the same thing with Unicode:
```
[^\u0000-\u007F]+
```
For unicode you can look at this 2 resources:
* [Code charts](http://www.unicode.org/charts/) list of Unicode ranges
* [This tool](http://kourge.net/projects/regexp-unicode-block) to create a regex filtered by Unicode block.
|
```
var words_in_text = function (text) {
var regex = /([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]+)/g;
return text.match(regex);
};
words_in_text('Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$');
// returns array ["Düsseldorf", "Köln", "Москва", "北京市", "إسرائيل"]
```
This regex will match all words in the text of any language...
|
Regular expression to match non-ASCII characters?
|
[
"",
"javascript",
"jquery",
"regex",
""
] |
I have read the post [here](http://www.julienlecomte.net/blog/2007/10/28/) about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my "please wait" animated GIF freezes while the local JavaScript is processing. Thanks!
```
function appendToSelect() {
$("#mySelect").children().remove() ;
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
var j = 1 ;
for (var i = 1; i < obj.data.length; i++) {
$("#mySelect").append(
'<option value="' + obj.data[i].value + '">'
+ obj.data[i].name
+ '</option>'
);
}
}
```
|
Here is a solution:
```
function appendToSelect() {
$("#mySelect").children().remove();
$("#mySelect").html(
'<option selected value="'+obj.data[0].value+'">'
+ obj.data[0].name
+ '</option>'
);
obj.data.splice(0, 1); // we only want remaining data
var appendOptions = function() {
var dataChunk = obj.data.splice(0, 10); // configure this last number (the size of the 'chunk') to suit your needs
for(var i = 0; i < dataChunk.length; i++) {
$("#mySelect").append(
'<option value="' + dataChunk[i].value + '">'
+ dataChunk[i].name
+ '</option>'
);
}
if(obj.data.length > 0) {
setTimeout(appendOptions, 100); // change time to suit needs
}
};
appendOptions(); // kicks it off
}
```
Not as elegant as [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) solution, but you get the idea. Basically, I am doing the same thing, but all in your one function rather than breaking it into a higher-order function like he does. I like his solution, but if you don't, perhaps this will work for you.
---
EDIT: For those that don't immediately see it, one of the main differences between this solution and [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) is that this solution allows you to set the size of the 'chunks' of data that is processed between each timeout. [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) times-out after *every single member* of the array is processed. If I get time, I will try to create a higher-order function to handle this so it is more elegant. No promises though! ;)
---
EDIT: So, here is my adaptation of [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) solution, which allows for setting a 'chunk' size and configuring the timeout value more easily:
```
function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) {
var itemIndex = 0;
(function() {
var remainingDataLength = (data.length - itemIndex);
var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength;
if(itemIndex < data.length) {
while(currentChunkSize--) {
workerCallback(data[itemIndex++]);
}
setTimeout(arguments.callee, timeout);
} else if(completionCallback) {
completionCallback();
}
})();
}
function appendToSelect() {
$("#mySelect").children().remove();
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
obj.data.splice(0,1); // we only want remaining data
incrementallyProcess(function(data) {
$("#mySelect").append(
'<option value="' + data.value + '">'
+ data.name
+ '</option>'
);
}, obj.data, 10, 100, removeAnimatedGifFunction); // last function not required...
}
```
Hope that helps - I think this combines the best of both solutions. **Notice**, the second anonymous function no longer uses the index value, but simply passes in the entire object (with the value and name properties); that makes it a bit cleaner, since the index of the current object really isn't *usually* that useful when iterating over things, IMO.
I am sure there are still things that could be done to make this even better, but that is left as an exercise for the reader. ;)
|
It just so happens that I was posting about this a moment ago [here](https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click#210931). Here is a timed loop function:
```
function processLoop( actionFunc, numTimes, doneFunc ) {
var i = 0;
var f = function () {
if (i < numTimes) {
actionFunc( i++ ); // closure on i
setTimeout( f, 10 )
}
else if (doneFunc) {
doneFunc();
}
};
f();
}
```
For your situation this would be used like this:
```
function appendToSelect () {
$("#mySelect").children().remove() ;
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
var j = 1 ;
processLoop(function (i){
$("#mySelect").append(
'<option value="' + obj.data[i].value + '">'
+ obj.data[i].name
+ '</option>'
);
}, obj.data.length);
}
```
You'll want to make sure that you have a closure or some other access to the obj variable within the iteration function.
Hope this helps.
|
How can I give control back (briefly) to the browser during intensive JavaScript processing?
|
[
"",
"javascript",
"jquery",
""
] |
I am working on a stored procedure with several optional parameters. Some of these parameters are single values and it's easy enough to use a WHERE clause like:
```
WHERE (@parameter IS NULL OR column = @parameter)
```
However, in some instances, the WHERE condition is more complicated:
```
WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId
FROM [UtilityWeb].[dbo].[GroupSites] AS gs
WHERE gs.GroupId = @NewGroupId))
```
When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn't bother me, doubling the execution time of a query is a definite problem.
Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?
Is this one of those instances where dynamic SQL would be a better solution?
|
The main problem is likely to be [parameter sniffing](http://omnibuzz-sql.blogspot.com/2006/11/parameter-sniffing-stored-procedures.html), and wildly different optimal execution plans depending on which of your parameters are NULL. Try running the stored proc with [RECOMPILE](http://www.sqlmag.com/Article/ArticleID/94369/sql_server_94369.html).
Contrary to some beliefs, Sql Server [*does*](http://weblogs.sqlteam.com/jeffs/archive/2008/02/22/sql-server-short-circuit.aspx) [do](http://technet.microsoft.com/en-us/cc678236.aspx) short circuit evaluations - though (as with all query optimizations) it may not be exactly what you wanted.
BTW - I would probably rewrite that portion of the query as a JOINed derived table:
```
SELECT *
FROM Table as si
JOIN (
SELECT SiteId
FROM [UtilityWeb].[dbo].[GroupSites]
WHERE GroupId = ISNULL(@NewGroupId, GroupId)
/* --Or, if all SiteIds aren't in GroupSites, or GroupSites is unusually large
--this might work better
SELECT @newGroupId
UNION ALL
SELECT SiteId FROM [UtilityWeb].[dbo].[GroupSites]
WHERE GroupId = @NewGroupId
*/
) as gs ON
si.SiteId = gs.SiteId
```
It may or may not influence the query plan, but it's a bit cleaner to me.
|
I would create separate queries for the parameter being available or not.
This will create simpler SQL, and the optimizer will do a better job.
Like this:
```
if (@parameter IS NULL) then begin
select * from foo
end
else begin
select * from foo where value = @parameter
end
```
In you have to many parameters to redesign like this, and you go for the dynamic sql solution, then also always use parameters, you might get bitten by the [SQL-Injection](https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks#2040) bug.
A combination is also possible. The most likely used query/queries you code in full, and get precompiled. All other combinations are created dynamically.
|
Working with optional stored procedure parameters
|
[
"",
"sql",
"database",
""
] |
The javascript `Date("mm-dd-yyyy")` constructor doesn't work for FF. It works fine for IE.
* IE : `new Date("04-02-2008")` => `"Wed Apr 2 00:00:00 EDT 2008"`
* FF2 : `new Date("04-02-2008")` => `Invalid Date`
So let's try another constructor: `Date("yyyy", "mm", "dd")`.
* IE: `new Date("2008", "04", "02");` => `"Fri May 2 00:00:00 EDT 2008"`
* FF: `new Date("2008", "04", "02");` => `"Fri May 2 00:00:00 EDT 2008"`
* IE: `new Date("2008", "03", "02");` => `"Wed Apr 2 00:00:00 EDT 2008"`
* FF: `new Date("2008", "03", "02");` => `"Wed Apr 2 00:00:00 EDT 2008"`
So the `Date("yyyy", "mm", "dd")` constructor uses an index of `0` to represent January.
How do I best deal with this other than subtracting 1 from the months?
|
It is the [definition of the Date object](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date) to use values 0-11 for the `month` field.
I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as separate parameters.
BTW, in Firefox,
```
new Date("04/02/2008");
```
It works fine for me - it will interpret slashes, but not hyphens. This proves my point that using a String to construct a Date object is problematic. Use explicit values for month/day/year instead:
```
new Date(2008, 3, 2);
```
|
nice trick indeed, which I just found out the hard way (by thinking through it).
But I used a more natural date string with a hyphen :-)
```
var myDateArray = "2008-03-02".split("-");
var theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]);
alert(theDate);
```
|
Javascript Date() constructor doesn't work
|
[
"",
"javascript",
"date",
""
] |
Consider the following interface in Java:
```
public interface I {
public final String KEY = "a";
}
```
And the following class:
```
public class A implements I {
public String KEY = "b";
public String getKey() {
return KEY;
}
}
```
Why is it possible for class A to come along and override interface I's final constant?
Try for yourself:
```
A a = new A();
String s = a.getKey(); // returns "b"!!!
```
|
Despite the fact that you are shadowing the variable it's quite interesting to know that you can change final fields in java as you can read [here](http://www.javaspecialists.co.za/archive/Issue096.html):
> **Java 5 - "final" is not final anymore**
>
> Narve Saetre from Machina Networks in Norway sent me a note yesterday,
> mentioning that it was a pity that we could change the handle to a
> final array. I misunderstood him, and started patiently explaining
> that we could not make an array constant, and that there was no way of
> protecting the contents of an array. "No", said he, "we can change a
> final handle using reflection."
>
> I tried Narve's sample code, and unbelievably, Java 5 allowed me to
> modify a final handle, even a handle to a primitive field! I knew that
> it used to be allowed at some point, but that it was then disallowed,
> so I ran some tests with older versions of Java. First, we need a
> class with final fields:
>
> ```
> public class Person {
> private final String name;
> private final int age;
> private final int iq = 110;
> private final Object country = "South Africa";
>
> public Person(String name, int age) {
> this.name = name;
> this.age = age;
> }
>
> public String toString() {
> return name + ", " + age + " of IQ=" + iq + " from " + country;
> }
> }
> ```
>
> **JDK 1.1.x**
>
> In JDK 1.1.x, we were not able to access private fields using
> reflection. We could, however, create another Person with public
> fields, then compile our class against that, and swap the Person
> classes. There was no access checking at runtime if we were running
> against a different class to the one that we compiled against.
> However, we could not rebind final fields at runtime using either
> class swapping or reflection.
>
> The JDK 1.1.8 JavaDocs for java.lang.reflect.Field had the following
> to say:
>
> * If this Field object enforces Java language access control, and the underlying field is inaccessible, the method throws an
> IllegalAccessException.
> * If the underlying field is final, the method throws an IllegalAccessException.
>
> **JDK 1.2.x**
>
> In JDK 1.2.x, this changed a bit. We could now make private fields
> accessible with the setAccessible(true) method. Access of fields was
> now checked at runtime, so we could not use the class swapping trick
> to access private fields. However, we could now suddenly rebind final
> fields! Look at this code:
>
> ```
> import java.lang.reflect.Field;
>
> public class FinalFieldChange {
> private static void change(Person p, String name, Object value)
> throws NoSuchFieldException, IllegalAccessException {
> Field firstNameField = Person.class.getDeclaredField(name);
> firstNameField.setAccessible(true);
> firstNameField.set(p, value);
> }
> public static void main(String[] args) throws Exception {
> Person heinz = new Person("Heinz Kabutz", 32);
> change(heinz, "name", "Ng Keng Yap");
> change(heinz, "age", new Integer(27));
> change(heinz, "iq", new Integer(150));
> change(heinz, "country", "Malaysia");
> System.out.println(heinz);
> }
> }
> ```
>
> When I ran this in JDK 1.2.2\_014, I got the following result:
>
> ```
> Ng Keng Yap, 27 of IQ=110 from Malaysia Note, no exceptions, no complaints, and an incorrect IQ result. It seems that if we set a
> ```
>
> final field of a primitive at declaration time, the value is inlined,
> if the type is primitive or a String.
>
> **JDK 1.3.x and 1.4.x**
>
> In JDK 1.3.x, Sun tightened up the access a bit, and prevented us from
> modifying a final field with reflection. This was also the case with
> JDK 1.4.x. If we tried running the FinalFieldChange class to rebind
> the final fields at runtime using reflection, we would get:
>
> > java version "1.3.1\_12": Exception thread "main"
> > IllegalAccessException: field is final
> > at java.lang.reflect.Field.set(Native Method)
> > at FinalFieldChange.change(FinalFieldChange.java:8)
> > at FinalFieldChange.main(FinalFieldChange.java:12)
> >
> > java version "1.4.2\_05" Exception thread "main"
> > IllegalAccessException: Field is final
> > at java.lang.reflect.Field.set(Field.java:519)
> > at FinalFieldChange.change(FinalFieldChange.java:8)
> > at FinalFieldChange.main(FinalFieldChange.java:12)
>
> **JDK 5.x**
>
> Now we get to JDK 5.x. The FinalFieldChange class has the same output
> as in JDK 1.2.x:
>
> ```
> Ng Keng Yap, 27 of IQ=110 from Malaysia When Narve Saetre mailed me that he managed to change a final field in JDK 5 using
> ```
>
> reflection, I was hoping that a bug had crept into the JDK. However,
> we both felt that to be unlikely, especially such a fundamental bug.
> After some searching, I found the JSR-133: Java Memory Model and
> Thread Specification. Most of the specification is hard reading, and
> reminds me of my university days (I used to write like that ;-)
> However, JSR-133 is so important that it should be required reading
> for all Java programmers. (Good luck)
>
> Start with chapter 9 Final Field Semantics, on page 25. Specifically,
> read section 9.1.1 Post-Construction Modification of Final Fields. It
> makes sense to allow updates to final fields. For example, we could
> relax the requirement to have fields non-final in JDO.
>
> If we read section 9.1.1 carefully, we see that we should only modify
> final fields as part of our construction process. The use case is
> where we deserialize an object, and then once we have constructed the
> object, we initialise the final fields, before passing it on. Once we
> have made the object available to another thread, we should not change
> final fields using reflection. The result would not be predictable.
>
> It even says this: If a final field is initialized to a compile-time
> constant in the field declaration, changes to the final field may not
> be observed, since uses of that final field are replaced at compile
> time with the compile-time constant. This explains why our iq field
> stays the same, but country changes.
>
> Strangely, JDK 5 differs slightly from JDK 1.2.x, in that you cannot
> modify a static final field.
>
> ```
> import java.lang.reflect.Field;
>
> public class FinalStaticFieldChange {
> /** Static fields of type String or primitive would get inlined */
> private static final String stringValue = "original value";
> private static final Object objValue = stringValue;
>
> private static void changeStaticField(String name)
> throws NoSuchFieldException, IllegalAccessException {
> Field statFinField = FinalStaticFieldChange.class.getDeclaredField(name);
> statFinField.setAccessible(true);
> statFinField.set(null, "new Value");
> }
>
> public static void main(String[] args) throws Exception {
> changeStaticField("stringValue");
> changeStaticField("objValue");
> System.out.println("stringValue = " + stringValue);
> System.out.println("objValue = " + objValue);
> System.out.println();
> }
> }
> ```
>
> When we run this with JDK 1.2.x and JDK 5.x, we get the following
> output:
>
> > java version "1.2.2\_014": stringValue = original value objValue = new
> > Value
> >
> > java version "1.5.0" Exception thread "main" IllegalAccessException:
> > Field is final at java.lang.reflect.Field.set(Field.java:656) at
> > FinalStaticFieldChange.changeStaticField(12) at
> > FinalStaticFieldChange.main(16)
>
> So, JDK 5 is like JDK 1.2.x, just different?
>
> **Conclusion**
>
> Do you know when JDK 1.3.0 was released? I struggled to find out, so I
> downloaded and installed it. The readme.txt file has the date
> 2000/06/02 13:10. So, it is more than 4 years old (goodness me, it
> feels like yesterday). JDK 1.3.0 was released several months before I
> started writing The Java(tm) Specialists' Newsletter! I think it would
> be safe to say that very few Java developers can remember the details
> of pre-JDK1.3.0. Ahh, nostalgia isn't what it used to be! Do you
> remember running Java for the first time and getting this error:
> "Unable to initialize threads: cannot find class java/lang/Thread"?
|
You are hiding it, it's a feature of "Scope". Any time you are in a smaller scope, you can redefine all the variables you like and the outer scope variables will be "Shadowed"
By the way, you can scope it again if you like:
```
public class A implements I {
public String KEY = "b";
public String getKey() {
String KEY = "c";
return KEY;
}
}
```
Now KEY will return "c";
Edited because the original sucked upon re-reading.
|
Why can final constants in Java be overridden?
|
[
"",
"java",
"interface",
"overriding",
"final",
""
] |
Is it possible with Axis2 and Eclipse to generate a Web Service client and have it use java types that you already have in packages instead of creating it's own types. Reason being of course if I have type A already created and it creates it's own Type A I can't just assign variable of type A to variable of type B.
The wsdl is being generated from a Web Service deployed to an application server.
If it's not possible to generate it from that would it be possible to generate a client from the already existing java files.
|
If you really want to reuse existing classes, you can call the Axis2 API directly without generating a client using wsdl2java. Below is some relatively simple code to call a web service. You just need to fill in the web service endpoint, method QName, expected return Class(es), and arguments to the service. You could reuse your existing classes as the return values or arguments.
If your web service is pretty complicated then you may find that you have to go deeper into the API to get this approach to work.
```
serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new EndpointReference("http://myservice");
options.setTo(targetEPR);
QName methodName = new QName("ns","methodName");
Class<?>[] returnTypes = new Class[] { String.class };
Object[] args = new Object[] { "parameter" };
Object[] response = serviceClient.invokeBlocking(methodName, args,
returnTypes);
```
|
You are generating the web service client from wsdl, correct?
The only thing that the wsdl2java tool knows about is the information in the wsdl, so it won't know about any types that you have already created.
If you can get the type information into the wsdl you may get it to work, although I have never tried.
If you want an easy way to copy from Type A to Type B then you could try [BeanUtils.copyProperties](http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)), as long as the setters and getters of Type A and Type B match.
|
Axis2 Web Service Client Generation - Types without modifying the client
|
[
"",
"java",
"code-generation",
"apache-axis",
"wsdl2java",
""
] |
OK, so I'm trying to teach myself the CakePHP framework, and I'm trying to knock up a simple demo app for myself.
I have the controllers, views and models all set up and working, but I want to do something slightly more than the basic online help shows.
I have a guitars\_controller.php file as follows...
```
<?php
class GuitarsController extends AppController {
var $name = 'Guitars';
function index() {
$this->set('Guitars', $this->Guitar->findAll());
$this->pageTitle = "All Guitars";
}
function view($id = null) {
$this->Guitar->id = $id;
$this->set('guitar', $this->Guitar->read());
// Want to set the title here.
}
}
?>
```
The 'Guitar' object contains an attribute called 'Name', and I'd like to be able to set that as the pageTitle for the individual page views.
Can anyone point out how I'd do that, please?
**NB**: I know that there is general disagreement about where in the application to set this kind of data, but to me, it is data related.
|
These actions are model agnostic so can be put in your app/app\_controller.php file
```
<?php
class AppController extends Controller {
function index() {
$this->set(Inflector::variable($this->name), $this->{$this->modelClass}->findAll());
$this->pageTitle = 'All '.Inflector::humanize($this->name);
}
function view($id = null) {
$data = $this->{$this->modelClass}->findById($id);
$this->set(Inflector::variable($this->modelClass), $data);
$this->pageTitle = $data[$this->modelClass][$this->{$this->modelClass}->displayField];
}
}
?>
```
Pointing your browser to /guitars will invoke your guitars controller index action, which doesn't exist so the one in AppController (which GuitarsController inherits from) will be run. Same for the view action. This will also work for your DrumsController, KeyboardsController etc etc.
|
You can set this in the controller:
```
function view($id = null) {
$guitar = $this->Guitar->read(null, $id);
$this->set('guitar', $guitar);
$this->pageTitle = $guitar['Guitar']['name'];
}
```
Or in the view:
```
<? $this->pageTitle = $guitar['Guitar']['name']; ?>
```
The value set in the view will override any value that may have already been set in the controller.
For security, you must ensure that your layout / view that displays the pageTitle html-encodes this arbitrary data to avoid injection attacks and broken html
```
<?php echo h( $title_for_layout ); ?>
```
|
CakePHP - How do i set the page title to an item name?
|
[
"",
"php",
"cakephp",
""
] |
Ruby can add methods to the Number class and other core types to get effects like this:
```
1.should_equal(1)
```
But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified?
*Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in Python, would allow this.*
To answer some of you: The reason I *might* want to do this is simply aesthetics/readability.
```
item.price.should_equal(19.99)
```
This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:
```
should_equal(item.price, 19.99)
```
This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
|
What exactly do you mean by Monkey Patch here? There are [several slightly different definitions](http://wikipedia.org/wiki/Monkey_patch).
If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes:
```
class Foo:
pass # dummy class
Foo.bar = lambda self: 42
x = Foo()
print x.bar()
```
If you mean, "can you change a class's methods at runtime and **make all of the instances of that class change after-the-fact**?" then the answer is yes as well. Just change the order slightly:
```
class Foo:
pass # dummy class
x = Foo()
Foo.bar = lambda self: 42
print x.bar()
```
But you can't do this for certain built-in classes, like `int` or `float`. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.
I'm not really clear on **why** you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!
|
No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. (Multiple interpreters in the same process are possible through the [C API](https://docs.python.org/3/c-api/init.html#sub-interpreter-support), and there has been [some effort](https://www.python.org/dev/peps/pep-0554/) towards making them usable at Python level.)
However, classes defined in Python code may be monkeypatched because they are local to that interpreter.
|
Can you monkey patch methods on core types in Python?
|
[
"",
"python",
"programming-languages",
"monkeypatching",
"fluent-interface",
""
] |
I'm using .NET 3.5 and I have a class, A, marked as internal sealed partial and it derives from System.Configuration.ApplicationSettingsBase. I then use an instance of this class in the following manner:
```
A A_Instance = new A();
A_Instance.Default.Save();
```
Why would the Visual C# compiler be complaining:
```
error CS0117: 'A' does not contain a definition for 'Default'
```
?
|
You are probably looking for this:
```
private static ServerSettings defaultInstance = ((ServerSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ServerSettings())));
public static ServerSettings Default
{
get { return defaultInstance; }
}
```
This is the code that gets generated by visual studio
|
.NET doesn't provide a 'Default' member in ApplicationSettingsBase from which to access any methods. What I failed to notice was that 'Default' was being used as a singleton of A. Thus, the sample code provided by gdean2323 gave me some guidance to the fix. The code to fix the problem required me adding the following code to class A (without necessary synchronization for simplicity):
```
private static A defaultInstance = new A();
public static A Default
{
get
{
return defaultInstance;
}
}
```
|
How come I can't see member 'Default' on a class derived from ApplicationSettingsBase?
|
[
"",
"c#",
".net",
""
] |
I've got an error in my build which says:
> Error 12 Cannot implicitly convert
> type
> 'System.Collections.Generic.IEnumerator< BaseClass>'
> to
> 'System.Collections.Generic.IEnumerator< IParentClass>'.
> An explicit conversion exists (are you
> missing a cast?)
Is it wrong to simply cast it away?
This is my code:
```
public Dictionary<Int32, BaseClass> Map { get; private set; }
public IEnumerator<BaseClass> GetEnumerator()
{
return this.Map.Values.GetEnumerator();
}
public IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
{
return this.GetEnumerator(); // ERROR!
}
```
My question is, can I just change this line:
```
return this.GetEnumerator();
```
to:
```
return (IEnumerator<IParentClass>)this.GetEnumerator();
```
(without any bad side effects)?
**Accepted Answer:**
I've changed the function to the following (after reading Jon Skeet's post):
```
IEnumerator<IParentClass> IEnumerable<IParentClass>.GetEnumerator()
{
return this.Map.Values.Cast<IParentClass>().GetEnumerator();
}
```
|
No you can't, because generics aren't covariant in C# at the moment. .NET itself has some support (for delegates and interfaces) but it's not really used yet.
If you were returning `IEnumerable<BaseClass>` instead of `IEnumerator<BaseClass>` (and assuming .NEt 3.5) you could use `Enumerable.Cast` - but you'll currently need to write your own extension method, e.g.
```
public static IEnumerator<TParent> Upcast<TParent, TChild>
(this IEnumerator<TChild> source)
where TChild : TParent
{
while (source.MoveNext())
{
yield return source.Current;
}
}
```
Alternatively in your case you could use Cast earlier:
```
return this.Map.Values.Cast<BaseClass>().GetEnumerator();
```
|
No, you can't, at least in C# 3.0 and below interface variance is not supported. See Eric Lippert's excellent series on this, and specifically [this one](http://blogs.msdn.com/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx).
|
Is it wrong to cast an enumerator of a child class to an enumerator of a parent class?
|
[
"",
"c#",
".net",
"generics",
"covariance",
""
] |
I have a native VC++ project that uses a dll (which is not in a project). Now, I must to put the dll in one the "Search Path Used by Windows to Locate a DLL"
[link](http://msdn.microsoft.com/en-us/library/7d83bc18(VS.80).aspx)
but I don't want the dll to sit in the exectuable or current or windows or system directory.
So my only option according to that is adding the path to the %PATH% environment variable.
Is there any other way?
Is there an elegant way to do so (adding to PATH)? should I do this on installation? should I be concerned if i'm doing this?
|
Summing up all the techniques I have found:
* If you use a managed project as the startup project (which is actually my case)
use Enviroment class
string temp = "myFullDirectoryPathToDll";
string temp2 =Environment.GetEnvironmentVariable("PATH") + ";" + temp;
Environment.SetEnvironmentVariable("PATH", temp2);
this, and I think MSDN should have stressed that, changes the environment variable PATH only in this process.
when debugging in VS the appPath doesn't 'work'
use properties->debug->environment and merge environment variables
[link](https://stackoverflow.com/questions/100543/how-do-i-set-specific-environment-variables-when-debugging-in-visual-studio)
* If you use a native:
do explicit linking - seems like big work for something simple,
maybe use appPath registery key on deployment
[link](http://www.codeguru.com/cpp/w-p/dll/print.php/c99),
nobody had a tested-and-proved answer
|
Here are a few suggestions:
* You could embed the dll as a resource in your main executable and then extract it to a temporary directory and load it from their using LoadLibrary and then get the relevant function addresses using GetProcAddress.
* You could modify you main processes search path using [SetDllDirectory()](http://msdn.microsoft.com/en-us/library/ms686203(VS.85).aspx) to include the location of the DLL. This avoids having to make any global changes to the system. And again use LoadLibrary/GetProcAddress to resolve the function addresses.
|
Native VC++ using external (not project) dll reference how to specify path to dll
|
[
"",
"c++",
"dll",
"visual-studio-2005",
"native",
""
] |
For an `std::map<std::string, std::string> variables`, I'd like to do this:
```
BOOST_CHECK_EQUAL(variables["a"], "b");
```
The only problem is, in this context `variables` is `const`, so `operator[]` won't work :(
Now, there are several workarounds to this; casting away the `const`, using `variables.count("a") ? variables.find("a")->second : std::string()` or even making a function wrapping that. None of these seem to me to be as nice as `operator[]`. What should I do? Is there a standard way of doing this (beautifully)?
**Edit:** Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.
|
```
template <typename K, typename V>
V get(std::map<K, V> const& map, K const& key)
{
std::map<K, V>::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : V();
}
```
Improved implementation based on comments:
```
template <typename T>
typename T::mapped_type get(T const& map, typename T::key_type const& key)
{
typename T::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : typename T::mapped_type();
}
```
|
Casting away const is wrong, because operator[] on map<> will create the entry if it isn't present with a default constructed string. If the map is actually in immutable storage then it will fail. This must be so because operator[] returns a non-const reference to allow assignment. (eg. m[1] = 2)
A quick free function to implement the comparison:
```
template<typename CONT>
bool check_equal(const CONT& m, const typename CONT::key_type& k,
const typename CONT::mapped_type& v)
{
CONT::const_iterator i(m.find(k));
if (i == m.end()) return false;
return i->second == v;
}
```
I'll think about syntactic sugar and update if I think of something.
...
The immediate syntactic sugar involved a free function that does a map<>::find() and returns a special class that wraps map<>::const\_iterator, and then has overloaded operator==() and operator!=() to allow comparison with the mapped type. So you can do something like:
```
if (nonmutating_get(m, "key") == "value") { ... }
```
I'm not convinced that is much better than:
```
if (check_equal(m, "key", "value")) { ... }
```
And it is certainly much more complex and what is going on is much less obvious.
The purpose of the object wrapping the iterator is to stop having default constructed data objects. If you don't care, then just use the "get" answer.
In response to the comment about the get being preferred over a comparison in the hope of finding some future use, I have these comments:
* Say what you mean: calling a function called "check\_equal" makes it clear that you are doing an equality comparison without object creation.
* I recommend only implementing functionality once you have a need. Doing something before then is often a mistake.
* Depending on the situation, a default constructor might have side-effects. If you are comparing, why do anything extra?
* The SQL argument: NULL is not equivalent to an empty string. Is the absence of a key from your container really the same as the key being present in your container with a default constructed value?
Having said all that, a default constructed object is equivalent to using map<>::operator[] on a non-const container. And perhaps you have a current requirement for a get function that returns a default constructed object; I know I have had that requirement in the past.
|
Idiomatic C++ for reading from a const map
|
[
"",
"c++",
"stl",
""
] |
In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php?
Example:
```
$sql ="select * from t1; select * from t2;";
$result = SomeQueryFunc($sql);
print_r($result[0]); // dump results for t1
print_r($result[1]); // dump results for t2
```
Can you do something like this?
|
This is called "multi-query." The mysql extension in PHP does not have any means to enable multi-query. The mysqli extension does allow you to use multi-query, but only through the multi\_query() method. See <http://php.net/manual/en/mysqli.multi-query.php>
Using multi-query is not recommended, because it can increase the potential damage caused by SQL injection attacks. If you use multi-query, you should use rigorous code inspection habits to avoid SQL injection vulnerability.
|
This should be possible with newer MySQL and the mysqli (improved) php extension.
I'm not sure if any DB abstraction layers support this.
See relevant [MySQL docs](http://dev.mysql.com/doc/refman/5.0/en/c-api-multiple-queries.html) and
[PHP docs](http://php.net/manual/en/mysqli.multi-query.php).
|
Multiple Data Tables in PHP/MySQL?
|
[
"",
"php",
"mysql",
"dataset",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.